【问题标题】:MVC Partial View not returning model on ajax postbackMVC 部分视图未在 ajax 回发时返回模型
【发布时间】:2010-12-30 13:53:31
【问题描述】:

我有一个视图,其中有一个局部视图,其中有一个文本框。主视图有一个 person 类型的模型,部分视图有一个 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>

局部视图

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

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 感谢您的回复,我进行了这些更改,但模型仍以 null 状态返回操作。
    • @user415394,您能看看在 AJAX 请求中使用 FireBug 实际发送的内容吗?另请查看我关于使用正确前缀的更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多