我想知道是否有可能在控制器函数中使用“params”参数,或者是否有类似的东西可以让我处理表单中X个条目。
例如,我有一个包含X个“名称”元素的表单,这些元素通过jQuery自动生成。这些名称元素的示例如下:
<input type="text" name="studentName1"></input>
<input type="text" name="studentName2"></input>
<input type="text" name="studentName3"></input>
现在,每次都有不同数量的学生姓名,因此这使我在控制器中处理表单数据变得相当复杂。我想到了以下两个示例,但是它们实际上是行不通的。
[HttpPost]
public ActionResult PostStudentNames(params string[] studentNames)
要么:
[HttpPost]
public ActionResult PostStudentNames(string[] formValues)
我可以达到类似的目的吗?
最佳答案
我只是想用一种可以用于此目的的不同方法来说明问题。如果更方便,则可以将模型绑定直接绑定到原始或复杂类型的集合。这里有两个例子:
index.cshtml:
@using (Html.BeginForm("ListStrings", "Home"))
{
<p>Bind a collection of strings:</p>
<input type="text" name="[0]" value="The quick" /><br />
<input type="text" name="[1]" value="brown fox" /><br />
<input type="text" name="[2]" value="jumped over" /><br />
<input type="text" name="[3]" value="the donkey" /><br />
<input type="submit" value="List" />
}
@using (Html.BeginForm("ListComplexModel", "Home"))
{
<p>Bind a collection of complex models:</p>
<input type="text" name="[0].Id" value="1" /><br />
<input type="text" name="[0].Name" value="Bob" /><br />
<input type="text" name="[1].Id" value="2" /><br />
<input type="text" name="[1].Name" value="Jane" /><br />
<input type="submit" value="List" />
}
Student.cs:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
HomeController.cs:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ListStrings(List<string> items)
{
return View(items);
}
public ActionResult ListComplexModel(List<Student> items)
{
return View(items);
}
}
ListStrings.cshtml:
@foreach (var item in Model)
{
<p>@item</p>
}
ListComplexModel.cshtml:
@foreach (var item in Model)
{
<p>@item.Id. @item.Name</p>
}
第一种形式只是绑定字符串列表。第二个将表单数据绑定到
List<Student>
。通过使用这种方法,您可以让默认的模型绑定器为您完成一些繁琐的工作。更新以发表评论
是的,您也可以这样做:
形成:
@using (Html.BeginForm("ListComplexModel", "Home"))
{
<p>Bind a collection of complex models:</p>
<input type="text" name="[0].Id" value="1" /><br />
<input type="text" name="[0].Name" value="Bob" /><br />
<input type="text" name="[1].Id" value="2" /><br />
<input type="text" name="[1].Name" value="Jane" /><br />
<input type="text" name="ClassId" value="13" /><br />
<input type="submit" value="List" />
}
控制器动作:
public ActionResult ListComplexModel(List<Student> items, int ClassId)
{
// do stuff
}
关于asp.net-mvc - 在 Controller 中接受参数或原始数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9281299/