0

当在 beginform 中提交数据时,我需要从控制器向视图发送 3 个变量(视图包)。由于下面的 AJAX 功能,目前我只能得到 1 个变量来回发。

查询/AJAX

   function autosubmit() {


        $.ajax({
            type: 'POST',
            url: this.action,
            data: $('form').serialize(),
           success: function (result) {
                    $('#one').html(result); //ViewBag.one
                    $('#two').html(result); //ViewBag.two
                    $('#three').html(result); //ViewBag.three
                                     }

        });


    }

形式:

@using (Html.BeginForm())
{
//form data automatically submits to controller
}


<div id="one">ajax data</div>
<div id="two">ajax data</div>
<div id="three">ajax data</div>

控制器

[HttpPost]
        public ActionResult Index(model stuff)
        {
         ViewBag.one = stuff.data1;
         ViewBag.two = stuff.data2;
         ViewBag.three = stuff.data3;
         Return(ViewBag.one, ViewBag.two,ViewBag.three)
         }
4

1 回答 1

7

忘记 ViewBag/ViewData。就好像它从未存在过一样。

使用 JSON:

[HttpPost]
public ActionResult Index(model stuff)
{
    var data = new 
    { 
        data1 = stuff.data1, 
        data2 = stuff.data2, 
        data3 = stuff.data3 
    };
    return Json(data);
}

然后消费:

$.ajax({
    type: 'POST',
    url: this.action,
    data: $('form').serialize(),
    success: function (result) {
        $('#one').html(result.data1);
        $('#two').html(result.data2);
        $('#three').html(result.data3);
    }
});
于 2012-06-13T14:05:16.997 回答