Reputation: 11464
I'm trying to update the Model with a background Ajax Post, below is my existing code
Javascript (Jquery)
var url = '@Url.Action("UpdateValue", "MyController")';
$.post(url, $('form').serialize(), function (view) {
//...
});
Controller
[HttpPost]
public ActionResult UpdateValue(MyViewModel model)
{
model.FileName = "NewValue";
return Json(new { success = true });
}
This code posts the existing model to controller and then I'm updating the field FileName
, but this does not seem to retain the updated value ("NewValue"). How to make it update the existing model with new value?
Upvotes: 0
Views: 885
Reputation: 4263
How about sending back the updated model:
[HttpPost]
public ActionResult UpdateValue(MyViewModel model)
{
model.FileName = "NewValue";
return Json(model);
}
Then in your $.post you can read the response and update your field.
As Brain Mains commented, you can't persist the model. Model is just nice way of accessing POSTed values.
Let's assume you are posting more values than FileName. So instead of doing this:
Request.Form["FileName"];
Request.Form["Id"];
Request.Form["Size"];
You just do this:
model.FileName
model.Id
model.Size
It's a lot cleaner and nicer to work with.
So If you follow the process of posting data:
User clicks a button > data is submitted via ajax > arrives to the asp.net engine > engine binds submitted data to the model > model is passed to controller > controller returns a result (and in this moment ... hackemate! ... the model is gone)
Upvotes: 0
Reputation: 50728
Setting model.FileName in the action doesn't do anything to the UI or the database. It depends on what you are trying to update, but if you are trying to update the UI, you would need to push the model back down to the client, and then reload the UI via client-JavaScript (since you are doing an AJAX post with JQuery).
Upvotes: 3