I have an action (Index) that return a View with a concrete model.
Inside that view (Is a calendar) I have two buttons to change months.
When I click one of those I call back Index action to that will return the same view with a modified model.
$("#right").live("click", function () {
$.post($(this).attr("href"), function (response) {
$("#wrapper开发者_JS百科").replaceWith($(response).filter("div#wrapper"));
});
return false;
});
So, I click #right and it call /Home/Index and Index return something like:
return View(new DateViewModel(dt, _bDays.GetDaysFromMonth(dt)));
So as you see, I replace div#wrapper with the new one. Perfect but...
Is there a way to get the model of the response? I mean, that action return a view with a model and apart from getting the concrete div I want the model.
Any idea?
I don't know why you would need the model in the AJAX callback, and thus there is probably a better solution than the one I am about to propose. So you could have your controller action render the partial view into a string and then return a JSON object containing both the HTML and the model:
[HttpPost]
public ActionResult MyAction()
{
MyViewModel model = new DateViewModel(dt, _bDays.GetDaysFromMonth(dt));
string html = RenderPartialToString("partialName", model);
return Json(new { Model = model, Html = html });
}
and in your AJAX callback:
$.post($(this).attr("href"), function (response) {
var model = response.Model;
var html = response.Html;
$("#wrapper").replaceWith($(html).filter("div#wrapper"));
});
One possible approach would be to call a separate controller action and return a JsonResult
:
[HttpPost]
public ActionResult MyAction()
{
return Json(new DateViewModel(dt, _bDays.GetDaysFromMonth(dt)));
}
This action will return a JSON representation of your ViewModel that you can reference in your AJAX response.
精彩评论