MVC Partial View not returning model on ajax postback
I have a view which has a partial view in it, which has a text box in it. The main view has a model of type person and the partial view a model of type person.other. When I do a ajax post back the other model is empty, I expected it to pick up the textbox data. This is the code;
Classes
public class Person
{
public string PersonID { get; set; }
public string Name { get; set; }
public Other Other { get; set; }
}
public class Other
{
public string OtherName { get; set; }
}
Controller
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
Person person = new Person();
person.Other = new Other();
person.Other.OtherName = "avbc";
return View(person);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test(Other other)
{
if (Request.IsAjaxRequest())
{
return PartialView("Test");
}
return null;
}
View
@model PartialViewTest.Models.Person
<h2>Index</h2>
<div id="mydiv">
@Html.Partial("Test", Model.Other)
</div>
PartialView
@model PartialViewTest.Models.Other
<h1>Test</h1>
@using (Html.BeginForm("Test", "Home", FormMethod.Post, new { id开发者_如何学编程 = "testForm" })) {
@Html.TextBoxFor(m => m.OtherName)
<input type="submit"/>
}
Jquery submit
$(document).ready(function () {
$('#testForm').submit(function () {
$.post($(this).attr("action"),
$(this).serialize(),
function (result) {
$('#mydiv').html(result);
});
);
});
Make sure you cancel the default form submission by returning false from the submit callback. Also you seem to be missing a closing }
:
$(document).ready(function () {
$('#testForm').submit(function () {
$.post($(this).attr("action"), $(this).serialize(), function (result) {
$('#mydiv').html(result);
});
return false;
});
});
Also you might need to modify your controller action like this because what is actually sent to the server is Other.OtherName=foo
:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test([Bind(Prefix="Other")]Other other)
精彩评论