ASP.NET MVC使用ajax将整个模型传递给控制器

时间:2015-09-03 13:29:14

标签: c# asp.net asp.net-mvc datatables

如何使用ajax将视图模型传递给控制器​​?请参阅下面的JS函数CreateTable():

我的控制器:

public ActionResult Index()
{
    var viewModel = new MyViewModel();

    return View(viewModel);
}

[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
    //CODE FOR GETTING STUFF HERE

    return View(viewModel);
}

public JsonResult GetResult(JQueryDataTableParamModel param, MyViewModel viewModel)
{
    //CODE FOR GETTING STUFF HERE

    return Json(new
    {
        sEcho = param.sEcho,
        aaData = viewModel.Data,
        iTotalRecords = viewModel.Data.Rows.Count,
        iTotalDisplayRecords = viewModel.DisplayRecords
    }, JsonRequestBehavior.AllowGet);
}

这是datatables.net处理的ajax部分:

function CreateTable() {
    var table = $('#dataTable').DataTable({
        "deferRender": true,
        "bServerSide": true,
        "sAjaxSource": "@Url.Action("GetResult")",
        "fnServerParams": function (aaData) {
            //here's my problem: HOW CAN I PUSH MY WHOLE MODEL HERE?
            aaData.push({ "name": "MyViewModel", "value": "@Model" });
        },
        "sPaginationType": "simple_numbers",
        "bProcessing": true,
        "oLanguage": { "sProcessing": "Loading..." },
        "aoColumns": [
            { "sName": "Col1" },
            { "sName": "Col2" },
            { "sName": "Col3" },
            { "sName": "Col3" },
            { "sName": "Col4" },
            { "sName": "Col5" }
        ]
    });
}

我的朋友告诉我,我也可以将整个模型从ajax传递给我的控制器,但我不知道该怎么做。请告知实施此更好的方法。谢谢。

3 个答案:

答案 0 :(得分:0)

您可以使用@Html.Raw(JsonConvert.SerializeObject(Model))序列化模型,以便您的功能如下所示:

"fnServerParams": function (aaData) {

            aaData.push({ name: "viewModel", value: @Html.Raw(JsonConvert.SerializeObject(Model)) });
        },

答案 1 :(得分:0)

只要你传递与你的模型具有相同属性的json对象,你应该安全回家,例如:

Model:

public class Language
    {
        public int ID { get; set; }
        public string Language1{ get; set; }
        public string Language2 { get; set; }
    }

Ajax:

$.ajax({
            url: '@Url.Action("Action", "Controller")',
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify({
                ID: 1,
                Language1: "English",
                Language2: "German",
                         }),
            dataType: 'json',


            success: function (data) {
                alert(data)
            }
        });

答案 2 :(得分:0)

使用fnServerParams时,您使用aoData.push({ "name": "customParam1", "value": $('#param1').val() }); aoData.push({ "name": "customParam2", "value": $('#param2').val() }); 将自定义参数发送到服务器。我不确定将整个模型作为单个参数传递,但您可以这样做:

param1

其中param2MyViewModel是从jQuery选择器检索的模型属性。

您的控制器方法需要从查询字符串中检索这些参数。像这样:

创建一个代表自定义参数的模型(这基本上会在您的示例中复制public class MyCustomParamModel { public string customParam1 { get; set; } public string customParam2 { get; set; } } ):

public JsonResult GetResult(JQueryDataTableParamModel param)
{
    NameValueCollection qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());

    var model = new MyCustomParamModel
    {
        customParam1 = qs["customParam1"],
        customParam2 = qs["customParam2"],
    }

在控制器中,解析查询字符串,获取自定义参数并将它们分配给模型

{{1}}

现在您已将模型数据存储在控制器中,您可以随意使用它。