简体   繁体   English

将数组形式传递给控制器

[英]Passing array form to controller

How can I send array of model from html view to controller. 如何将模型数组从html视图发送到控制器。 In this code I receive null on controller parameter. 在这段代码中,我在控制器参数上收到null。

public class PropModel
{
    public string Name { get; set; }
    public string Value { get; set; }
}

[HttpPost]
public ActionResult Index(PropModel[] model)
{
        foreach (var r in model)
        {
            //Do somethings
        }
        return View();
}

View: 视图:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title></title>
</head>
<body>
    <div>

        @using (Html.BeginForm())
        {
            for (int i = 0; i < 3; i++)
            {
                @Html.TextBox("Name")
                @Html.TextBox("Value")
            <br/>
            }
            <input type="submit" value="submit"/>
        }
    </div>
</body>
</html>
@model List<PropModel>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title></title>
</head>
<body>
    <div>

        @using (Html.BeginForm())
        {
            for (int i = 0; i < 3; i++)
            {
                @Html.TextBoxFor(m=>this.Model[i].Name)
                @Html.TextBoxFor(m=>this.Model[i].Value)
            <br/>
            }
            <input type="submit" value="submit"/>
        }
    </div>
</body>
</html>

The magic is in how you name your input fields. 魔术在于您如何命名输入字段。

I could be wrong, but I think the controller will interpret that post as as array of Name s and an array of Value s. 我可能是错的,但我认为控制器会将该帖子解释为Name数组和Value数组。 You could try to either update your method signature: 您可以尝试更新方法签名:

[HttpPost]
public ActionResult Index(string[] Name, string[] Value)
{

}

Or build your "model" as an array of objects using JSON. 或使用JSON将“模型”构建为对象数组。

You can use EditorTemplates to handle this situation. 您可以使用EditorTemplates处理这种情况。

Let's make a new viewmodel for our view. 让我们为视图创建一个新的视图模型。

public class PropListVM
{
    public List<PropModel> Props { set; get; }
    public PropListVM()
    {
        Props = new List<PropModel>();
    }
}

Now in our GET Action, we will create an object of this new viewmodel, Set the Props collection and send to our view. 现在,在GET Action中,我们将创建此新视图模型的对象,设置Props集合并将其发送到我们的视图。

public ActionResult Index()
{           
    var vm = new PropListVM { Props = GetPropsFromSomeWhere() };
    return View(vm);
}
private List<PropModel> GetPropsFromSomeWhere()
{
    var list = new List<PropModel>();
    //Hard coded for demo. You may replace it with DB items
    list.Add(new PropModel { Name = "Detroit", Value = "123" });
    list.Add(new PropModel { Name = "Ann Arbor", Value = "345" });
    return list;
}

Now Let's create an EditorTemplates . 现在让我们创建一个EditorTemplates Go to ~/Views/YourControllerName and Create a Folder called "EditorTemplates" and create a new view there with the same name as of the Property Name( PropModel.cshtml ) 转到~/Views/YourControllerName并创建一个名为“ EditorTemplates”的文件夹,并在其中创建一个与属性名称相同的新视图( PropModel.cshtml

在此处输入图片说明

Add this code to your new editor template. 将此代码添加到新的编辑器模板中。

@model ReplaceYourNameSpaceHere.PropModel
<div>
    Name :@Html.TextBoxFor(s=>s.Name) <br />
    Value : @Html.TextBoxFor(s=>s.Value)
</div>

Make sure to replace ReplaceYourNameSpaceHere with your actual namespace where the PropModel class is available. 确保使用PropModel类可用的实际名称空间替换ReplaceYourNameSpaceHere

Now Let's go back to our original view( Index.cshtml ) which is strongly typed to an instance of our PropListVM viewmodel. 现在,让我们回到原始视图( Index.cshtml ),该视图被强类型PropListVM视图模型的实例。

@model ReplaceYourNameSpaceHere.PropListVM
@using (Html.BeginForm())
{
<div>
    @Html.EditorFor(s=>s.Props)        
    <input type="submit" value="submit"/>
</div>
}

Now let's have an action method to handle the form posting, You will have a parameter of type PropListVM and MVC model binding will bind the properties of this objects from the form posted. 现在,我们有一个操作方法来处理表单发布,您将拥有PropListVM类型的参数,并且MVC模型绑定将从发布的表单中绑定此对象的属性。 You can check the Props property of this object and loop through each items. 您可以检查此对象的Props属性并遍历每个项目。

[HttpPost]
public ActionResult Index(PropListVM model)
{
    foreach (var prop in model.Props)
    {
        string s = prop.Name;
        //Do cool somethings
    }
    // return or redirect now
    //If we are returning the posted model back to the form, 
    //reload the Props property.
    model.Props = GetPropsFromSomeWhere();
    return View(model);
}

And the result is ??? 结果是??? Profit !!!!!! 利润!!!!!!

In my example, I sent 2 PropModel items with Name and Value properties set, But if you want some empty form, Simply add PropModel objects without initializing any property values. 在我的示例中,我发送了两个PropModel了Name和Value属性的PropModel项,但是,如果您想要一些空表单,只需添加PropModel对象而无需初始化任何属性值。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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