是否可以使用jquery ajax将不同的模型类型传递给控制器​​?

时间:2015-02-06 07:45:23

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

我们说我有一个具有SubForum属性的论坛模型。

查看:

@model Forum

@using (@Html.BeginForm("DoSomething", "Forum", FormMethod.Post, new { id= "SubForumForm" }))
{
     @Html.TextBoxFor(model => model.subForum.test1)
     @Html.TextBoxFor(model => model.subForum.test2)
     <input id="btn" type="button" value="CLICK" />
}

型号:

public class Forum
{
     public subForum SubForum { get; set; }
)

控制器:

[HttpPost]
public ActionResult DoSomething(model SubForum)
{
     if (ModelState.isValid)
     {
          //do something with the model
     }
}

我想通过jquery ajax将SubForum属性传递给我的控制器:

   $('#btn').click(function () {
        if($('#SubForumForm').valid()) {
            $.ajax({
                type: "POST",
                url: BASE_URL + "Forum/DoSomething/",
                dataType: 'json',
                data: $('#SubForumForm').serializeArray(),
                beforeSend: function (xhr) {
                },
                success: function (data) {
                },
                error: function (data) {
                }
            });
        }
    });

我在DoSomething方法中的模型SubForm将始终返回null,但如果我将控制器方法参数更改为:

 public ActionResult DoSomething(model Forum)

所以我的问题:是否可以将不同的模型类型传递给控制器​​或jquery ajax只有在视图(@model)中传递完全相同的模型时才有效?

对于糟糕的英语,任何帮助都会受到赞赏和抱歉。

1 个答案:

答案 0 :(得分:1)

您可以使用Prefix属性

[Bind]属性
[HttpPost]
public ActionResult DoSomething([Bind(Prefix = "subForum")]SubForum model)

它当前未绑定的原因是发布的值为subForum.test1="SomeValue",但由于typeof SubForum不包含名为subForum的属性,因此绑定失败。该属性实际上剥离了指定的前缀,因此它将变为test1="SomeValue",因为typeof SubForum确实包含名为test1的属性