我在 View 页面上有一个简单的表单,作为用户控件实现,看起来像这样:
<%=Html.BeginForm("List", "Building", FormMethod.Post) %>
//several fields go here
<%Html.EndForm(); %>
有两个问题我想解决,第一个是我希望接收它的 Controller 方法采用用户控件的类型参数。目标是避免将表单的所有字段放入方法的参数列表中。 Controller 方法目前看起来像这样:
[AcceptVerbs("Post")]
public ActionResult List(string capacityAmount)
{
ProfilerDataDataContext context = new ProfilerDataDataContext();
IEnumerable<Building> result = context.Buildings.OrderBy(p => p.SchoolName);
ViewData["Boroughs"] = new SelectList(Boroughs.BoroughsDropDown());
return View(result);
}
表单中的其余字段将用于针对建筑物类型进行搜索。
表单发布很好,我可以按照您期望的方式搜索容量,但在我向搜索添加参数时,我可以闻到前方的丑陋。
其次,较小的问题是当页面呈现 BeginForm 标记时将字符串“System.Web.Mvc.Form”呈现到页面。我该如何让它消失?
最佳答案
1) 使用 FormCollection 作为参数:
public ActionResult List(FormCollection searchQuery)
现在您可以迭代 FormCollection 并从您的搜索表单中获取键/值搜索词。
2) 从 BeginForm 中删除“=”:
<% Html.BeginForm("List", "Building", FormMethod.Post) %>
也就是说,你should really be using ,嗯……使用:
<% using (Html.BeginForm("List", "Building", FormMethod.Post)) { %>
<% } %>
关于c# - 在 ASP.net MVC 中实现表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/483545/