MVC BeginForm - 从控制器返回三个不同的ajax文本字符串

时间:2012-06-13 14:03:10

标签: c# jquery ajax asp.net-mvc

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

JQUERY / 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
                                     }

        });


    }

FORM:

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

CONTROLLER

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

1 个答案:

答案 0 :(得分: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);
    }
});