如何安全地访问FormCollection中的密钥组?

时间:2011-10-10 17:20:56

标签: asp.net-mvc-3 http

我有一个table,其中每个tr的{​​{1}}元素input设置为每行唯一的值。

例如,

name

在发布时

    <td>
        <input data-field="opps" type="text" value="somevalue" name="@item.Code" />
    </td>
    <td>
        <input data-field="asc" type="text" value="somevalue2" name="@item.Code" />
    </td>

我的System.Web.MVC.FormCollection按照我定义[HttpPost] public ActionResult Update(FormCollection collection) { try { //doin work on collection...order assumed static return RedirectToAction("Index"); } catch { return View(); } } 的顺序进行分组。我不想假设订单,但无法访问我的<td>,我不确定我还能做什么(也许我可以将数据字段值作为前缀添加到data-field并将它们与自定义集合和Regex放在一起......但这看起来很糟糕。

有没有办法访问name?这样我就不会在View中重新排序或添加新列了。

1 个答案:

答案 0 :(得分:1)

假设您有一个类(模型)定义如下:

public class MyModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

在您的控制器中,您可能有一个名为Create的操作,如下所示:

[HttpGet]
public ViewResult Create()
{
    MyModel sampleModel = new MyModel();
    return View(sampleModel);
}

[HttpPost]
public ActionResult Create(MyModel sampleModel)
{
    if (ModelState.IsValid)
    {
        TempData["Error"] = "There were errors. Please correct the problem and submit again";
        return View(sampleModel);
    }

    // At this point everything is fine and you can access data in your sampleModel
    if (sampleModel.Age >= 16)
    {
        return RedirectToAction("LegalAccess");
    }
    else
    {
        TempData["Error"] = "You must be 16 or over to access this site";      
        return RedirectToAction("AgeRestriction");
    }
}

当您创建使用MyModel作为模型的强类型视图时,您可以将其定义为:

@model MyModel

@{
    Layout = "~/Shared/_Layout.cshtml";
}

@using (Html.BeginForm()) 
{
    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)
    <br />
    @Html.LabelFor(m => m.LastName)
    @Html.TextBoxFor(m => m.LastName)
    <br />
    @Html.LabelFor(m => m.LastName)
    @Html.TextBoxFor(m => m.LastName)

    <input type="submit" value="Submit" />        
}

当您提交此表单时,模型绑定器将在后台使用Request.Form将此表单中的数据复制到它在后台创建的MyModel类型的对象中。此新对象将传递给处理HTTP POST方法的操作。使用此方法,您将获得强类型对象,而不必担心FormCollection中的项目顺序。

我希望我能回答你的问题。

顺便说一句。我在没有Visual Studio的情况下编写了这个,所以我希望没有错误。 : - )