2009-01-27 88 views
3

我有一個視圖頁面上一個簡單的形式,爲用戶控件實現,這看起來是這樣的:在ASP.net實現形式MVC

<%=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); 
    } 

窗體中其餘的字段將用於對建築物類型進行搜索。

表單帖子很好,我可以按照您期望的方式在容量上進行搜索,但是在向搜索添加參數時,我可以嗅到前面的醜陋。

其次,較小的問題是,當頁面呈現BeginForm標記時,呈現字符串「System.Web.Mvc.Form」到頁面。我如何讓它消失?

回答

6

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)) { %> 
<% } %> 
+0

我使用你的使用建議,但控制器方法永遠不會觸發。我必須錯過別的東西...... – KevDog 2009-01-27 14:39:07

0

如果我正確理解你的問題,你使用html助手並創建名爲的輸入:

<%=Html.TextBox("building.FieldNumber1")%> 
<%=Html.TextBox("building.FieldNumber2")%> 

您應該能夠使用以下方式訪問數據:

public ActionResult List(Building building) 
{ 
    ... 
    var1 = building.FieldNumber1; 
    var2 = building.FieldNumber2; 
    ... 
} 

,如果你的動作是做取決於是否提交表單上兩個不同的東西:

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

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

如果任何人懷疑「使用」模式Html.BeginForm全 - 意識到, IDE足夠聰明,可以匹配開頭的'{'和結尾'}',這可以很容易地看到你的表單開始和結束的位置。

另外<%Html.EndForm(); %>需要一個分號,我不知道我喜歡:)