C# 在ASP.net MVC中实现表单

C# 在ASP.net MVC中实现表单,c#,.net,asp.net-mvc,forms,views,C#,.net,Asp.net Mvc,Forms,Views,我在视图页面上有一个简单的表单,作为用户控件实现,如下所示: <%=Html.BeginForm("List", "Building", FormMethod.Post) %> //several fields go here <%Html.EndForm(); %> [AcceptVerbs("Post")] public ActionResult List(string capacityAmount) { ProfilerData

我在视图页面上有一个简单的表单,作为用户控件实现,如下所示:

<%=Html.BeginForm("List", "Building", FormMethod.Post) %>

//several fields go here

<%Html.EndForm(); %>
[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);
    }

//这里有好几块地
我希望解决两个问题,第一个问题是,我希望接收该问题的控制器方法采用用户控件的类型参数。目标是避免将表单的所有字段都放入方法的参数列表中。控制器方法当前如下所示:

<%=Html.BeginForm("List", "Building", FormMethod.Post) %>

//several fields go here

<%Html.EndForm(); %>
[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);
    }
[AcceptVerbs(“Post”)]
公共操作结果列表(字符串容量计数)
{
ProfilerDataContext=新ProfilerDataContext();
IEnumerable result=context.Buildings.OrderBy(p=>p.SchoolName);
ViewData[“Boroughs”]=新的选择列表(Boroughs.BoroughsDropDown());
返回视图(结果);
}
表单中的其余字段将用于对建筑物类型进行搜索

表单帖子很好,我可以按照您期望的方式搜索容量,但我可以在搜索中添加参数时闻到前方的丑陋

其次,较小的问题是,当页面呈现BeginForm标记时,会将字符串“System.Web.Mvc.Form”呈现给页面。如何消除这种情况?

1)使用FormCollection作为参数:

public ActionResult List(FormCollection searchQuery)
现在,您可以迭代FormCollection并从搜索表单中获取键/值搜索词

2) 从以下位置删除“=”:

<% Html.BeginForm("List", "Building", FormMethod.Post) %>

也就是说,你,嗯。。。使用:

<% using (Html.BeginForm("List", "Building", FormMethod.Post)) { %>
<% } %>

如果我正确理解了您的问题,您可以使用html帮助程序并创建名为:

<%=Html.TextBox("building.FieldNumber1")%>
<%=Html.TextBox("building.FieldNumber2")%>
如果您的操作是根据提交的表格做两件不同的事情:

public ActionResult List()
{
    //some code here
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult List(Building building)
{
   ...
   var1 = building.FieldNumber1;
   var2 = building.FieldNumber2;
   ...
}

如果有人对Html.BeginForm的整个“使用”模式持怀疑态度,那么请认识到IDE足够智能,可以将开头的
'{'
与结尾的
'}
匹配起来,这样就很容易看到表单的开始和结束位置


还需要一个分号,我不确定我是否喜欢:)

我正在使用您的using suggestion,但controller方法从不激发。我必须错过一些其他的东西…当你提交时会发生什么?如果什么都没有发生,那么我会非常仔细地查看提交给服务器的内容。我通常用firebug来做这个。如果表单没有提交任何内容或提交了错误的内容,那么请检查呈现的HTML。我的错误是没有执行EndForm调用。控制器方法正确点火。我非常感谢你的回答。