2012-02-15 17 views
2

我有一個類,看起來像這樣:ASP.NET MVC表單元素名代

public class UserListVM 
{ 
    public SearchModel SearchModel { get; set; } 
    public PagedList<User> Users { get; set; } 
} 

public class SearchModel 
{ 
    public string Text { get; set; } 
    /* other properties */ 
} 

我送UserListVM我的看法,但在行動接受SearchModel

public ActionResult Search(SearchModel filter) 
{ 
     UserListVM model = new UserListVM(); 

     model.Users = userService.GetUsers(filter); 
     model.SearchModel = filter; 

     return View(model); 
} 

我的看法是:

@model UserListVM 

<form> 
    @Html.TextBoxFor(m => Model.SearchModel.Text) 
</form> 

但是,這產生:

<input id="SearchModel_Text" name="SearchModel.Text" type="text" value=""> 

其中發送UserListVM而不是SearchModel。我怎樣才能得到它產生這樣的:

<input id="Text" name="Text" type="text" value=""> 
+0

你爲什麼要傳遞一個UserListVM當它需要一個SearchModel的看法?您的視圖不會使用SearchModel以外的任何內容。 – 2012-02-15 23:22:05

回答

2
@Html.TextBoxFor(m => m.SearchModel.Text, new { id = "Text" }) 

利用重載TextBoxFor()方法,它採用第二object參數(稱爲htmlAttributes)。在這裏,您可以指定HTML屬性以應用於您當前正在使用的DOM元素(在這種情況下,您的元素爲input)。

編輯:我相信你的lambda表達式是錯誤的。變化:

@Html.TextBoxFor(m => Model.SearchModel.Text) 

@Html.TextBoxFor(m => m.SearchModel.Text) 
// htmlAttributes omitted to show the issue 

編輯編輯:事實證明,即使有規定name屬性,它會根據什麼形式需要一個POST必要的渲染字段(一個或多個)。

編輯編輯編輯:嘗試是明確與FormExtensions.BeginForm()

@using (Html.BeginForm("Search", "YourController", FormMethod.Post, null)) 
{ 
    @Html.TextBoxFor(m => m.SearchModel.Text) 
} 

使用此爲您<form />元素的substite。

+0

使用'LabelFor',我需要將它作爲一個字符串給它? – 2012-02-15 21:54:12

+0

@Lolcoder如果我正確理解你的問題,那麼是的。把這個'object'('htmlAttributes')看作爲設置HTML元素屬性值的直接方式。 – 2012-02-15 21:55:42

+0

當我嘗試這個時,只有id被改變,不知怎麼的名字沒有被覆蓋。 – 2012-02-15 22:03:51

2

爲您的SearchModel創建一個局部視圖,並使用Html.Partial調用它。然後,從局部視圖中,做所有的EditorFor/TextBoxFor擴展的

你的觀點 - UserList.cshtml:

@model UserListVM 

@using (Html.BeginForm()) 
{ 
    @Html.Partial("Search", Model.SearchModel) 
} 

你的觀點 - Search.cshtml:

@model SearchModel 

@Html.TextAreaFor(m => m.Text) 
0

Assumming有更多的視圖比你已經顯示,爲什麼不只是讓你的搜索方法採用UserListVM模型。它只包含對用戶的空引用,所以在帖子中沒有發送額外的數據。

0

嘗試做手工是這樣的:

@Html.TextBox("Text", Model.SearchModel.Text)