简体   繁体   中英

Is it possible to pass different model type to controller using jquery ajax?

Let's say I have a Forum model with SubForum property.

View:

@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" />
}

Model:

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

Controller:

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

And I want to pass SubForum property to my controller with jquery ajax :

   $('#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) {
                }
            });
        }
    });

My model SubForm in DoSomething method will always return null, but it works if I change the controller method parameter to :

 public ActionResult DoSomething(model Forum)

So my question : Is it possible to pass different model type to controller or jquery ajax only works if you pass the exact same model in your View (@model)?

Any help will be appreciated and sorry for bad english.

You can use the Prefix property of the [Bind] attribute

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

The reason it does not currently bind is that the posted values are subForum.test1="SomeValue" , but since typeof SubForum does not contain a property named subForum , binding fails. The attribute essentially strips the specified prefix so it becomes test1="SomeValue" which will bind because typeof SubForum does contain a property named test1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM