MVC Partial View没有在ajax回发上返回模型

时间:2010-12-30 13:53:31

标签: asp.net-mvc asp.net-mvc-3

我有一个视图,里面有一个局部视图,里面有一个文本框。主视图具有person类型的模型,而partial视图具有person.other类型的模型。当我回复ajax后,其他模型是空的,我希望它能够获取文本框数据。这是代码;

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; }
    }

控制器

[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;
        }

查看

@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提交

$(document).ready(function () {

    $('#testForm').submit(function () {

        $.post($(this).attr("action"),
             $(this).serialize(),
            function (result) {
                $('#mydiv').html(result);
            });
        );
});

1 个答案:

答案 0 :(得分:1)

确保通过从提交回调中返回false来取消默认表单提交。此外,您似乎错过了结束}

$(document).ready(function () {
    $('#testForm').submit(function () {
        $.post($(this).attr("action"), $(this).serialize(), function (result) {
            $('#mydiv').html(result);
        });
        return false;
    });
});

此外,您可能需要像这样修改控制器操作,因为实际发送到服务器的是Other.OtherName=foo

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test([Bind(Prefix="Other")]Other other)