循环遍历复杂的POST表格字段

时间:2017-06-24 19:34:54

标签: asp.net-mvc asp.net-core asp.net-core-mvc

我有View动态呈现HTML。最终看起来像这样:

<form asp-controller="Home" asp-action="Save">
    <!-- Location widget class -->
    <input name="widgets[0].Name" />
    <input name="widgets[0].Type" value="Location" />
    <input name="widgets[0].Location" />

    <!-- Rating widget class -->
    <input name="widgets[1].Name" />
    <input name="widgets[1].Type" value="Rating" />
    <input name="widgets[1].Rating" />
    <input name="widgets[1].Remark" />

    <button type="submit">Submit</button>
</form>

每个&#34;小部件&#34;在一个单独的类中定义,如下所示: (资源NameType在父Widget类中定义)

public class Location : Widget
{
    public string Location {get;set;}
}

public class Rating : Widget
{
    public string Rating {get;set;}
    public string Remark {get;set;}
}

我遇到的问题是我必须POST将此表格发回给我的控制器。在那里,我希望能够做到这样的事情:

public IActionResult Save()
{
    var req = HttpContext.Request;

    foreach(var widget in req.widgets)
    {
        if(widget.Type == "Location") { 
            ... 
        }
        else if(widget.Type == "Rating") { 
            ... 
        }
        // etc.
    }
}

似乎我不能简单地从HttpContext.Request对象中读出类似的属性。

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

如果将IFormCollection对象添加到params,则可以将表单字段读为KeyValuePairs:

public IActionResult Save(IFormCollection formCollection)

关于你的具体问题,我相信你可以这样做:

我没有测试过以下代码,但我几乎可以肯定它有效!

public async Task<IActionResult> Save(List<Widget> widgets)
{
    for(var i = 0; i < widgets.Count; i++)
    {
        if(widgets[i].Type == "Location") { 
            var locationObj = new Location();
            await TryUpdateModelAsync(locationObj, $"widgets[{i}]");
            //Do whatever you want with the object.
        }
        else if(widgets[i].Type == "Rating") { 
            var ratingObj = new Rating();
            await TryUpdateModelAsync(ratingObj, $"widgets[{i}]");
            //Do whatever you want with the object. 
        }
        // etc.
    }
    ...
}

请告诉我它是否有帮助!