我SearchUsers查看看起來這樣:與MVC簡單搜索,以查看
<% foreach (var item in Model)
我想要的模型與數據綁定:
<% using (Html.BeginForm())
{%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.Label("Search Users:" %>
</div>
<div class="editor-field">
<%= Html.TextBox("keyword") %>
</div>
<p>
<input type="submit" value="Search" />
</p>
</fieldset>
<%} %>
<table>
<tr>
<th>
TITLE
</th>
<th>
FIRSTNAME
</th>
<th>
LASTNAME
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%= Html.ActionLink("GetProfile", "User", new { username=item.USERNAME }) %>
|
<%= Html.ActionLink("UpdateProfile", "User", new { username=item.USERNAME })%>
</td>
<td>
<%= Html.Encode(item.TITLE) %>
</td>
<td>
<%= Html.Encode(item.FIRSTNAME) %>
</td>
<td>
<%= Html.Encode(item.LASTNAME) %>
</td>
</tr>
<% } %>
一個例外是在那個去行拋出只有在我執行搜索後,但它似乎嘗試綁定數據時,我第一次訪問此視圖。我如何防止這種情況?
我的控制器是這樣的:
public ActionResult SearchUsers()
{
return View();
}
[HttpPost]
public ActionResult SearchUsers(FormCollection collection)
{
DBServiceLinq db = new DBServiceLinq();
Acctinfo acct = new Acctinfo();
acct = db.SearchUsers(collection["keyword"]);
return View(acct);
}
我SearchUsers方法看起來如:
[WebMethod]
public Acctinfo SearchUsers(string keyword)
{
var q = from acctinfo in db.Acctinfos
where acctinfo.USERNAME.Contains(keyword)
select acctinfo;
Acctinfo a = new Acctinfo();
a = q.First();
return a;
}
LINQ延遲執行枚舉序列只有當模型被訪問,可能。 ToList()在控制器中? – bzlm
添加了我的控制器/方法的外觀。我哪裏做錯了? @bzlm –
如果您將其更改爲'acct = db.SearchUsers(collection [「keyword」])。ToList();'您將在控制器中發生錯誤。 [閱讀LINQ中的延遲執行*](http://www.codeguru.com/columns/vb/article.php/c16935)假設在視圖呈現時執行實際搜索這違背了模型,視圖和控制器責任的原則。 – bzlm