开发者

Binding elements created in JQuery to a parameter in my controller

开发者 https://www.devze.com 2023-02-05 08:16 出处:网络
I have a form in my view with the following two html elements (these elements were created dynamically by JQuery and were not bound to the view using the Model).

I have a form in my view with the following two html elements (these elements were created dynamically by JQuery and were not bound to the view using the Model).

<input id="JsonCommand_0__NickName" type"radio" name="JsonCommand[0].NickName" va开发者_如何学JAVAlue="name1" checked>
<input id="JsonCommand_1__NickName" type"radio" name="JsonCommand[1].NickName" value="name2" checked>

I have the following class:

public class JsonCommand
{
    public string NickName { get; set; }
}

I have the following controller:

[HttpPost, Authorize, Compress]
public ActionResult Edit(IEnumerable<JsonCommand> command)
{
    ....
}

I am using JQuery.Form plugin to post to this controller. Is it possible for me to serialize the form collection into a JsonCommand objects this way? Currently when I try I get a null value for command.

Is there any way I can create a collection on the client side and bind it to my JsonCommand object?

Thanks


The following works perfectly fine for me:

Model:

public class JsonCommand
{
    public string NickName { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new[] 
        {
            new JsonCommand { NickName = "name1" },
            new JsonCommand { NickName = "name2" },
        });
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<JsonCommand> command)
    {
        return Json(new { message = "ok" });
    }
}

View (~/Views/Home/Index.aspx):

<script type="text/javascript" src="https://github.com/malsup/form/raw/master/jquery.form.js?v2.43"></script>
<script type="text/javascript">
    $('form').ajaxForm(function (result) {
        alert(result.message);
    });
</script>

<% using (Html.BeginForm()) } %>
    <%: Html.EditorForModel() %>
    <input type="submit" value="OK" />
<% } %>

Editor template (~/Views/Home/EditorTemplates/JsonCommand.aspx):

<%@ Control 
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.JsonCommand>" %>
<%: Html.RadioButtonFor(x => x.NickName, Model.NickName) %>

Also note that radio buttons are usually bound to boolean values instead of strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消