您已經在控制器操作中聲明瞭UserId
變量。你並不需要再次從Request
取,
public class SearchController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SearchUser(string UserId)
{
User user = ... go and fetch the user given the user id
// from wherever your users are stored (a database or something)
return View(user);
}
}
現在你可以把你的觀點強類型的User
類,並有顯示結果的部分:
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.User>"
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<div align="center">
<% using (Html.BeginForm("SearchUser", "Search")) { %>
<table align="center">
<tr>
<td class="label">
Enter ID:
</td>
<td>
<input type="text" name="UserId" id="UserId" />
</td>
</tr>
<tr>
<td>
<button class="searchButton" id="searchButtong">Search</button>
</td>
</tr>
</table>
<% } %>
</div>
<hr />
<% if (Model != null) { %>
<!-- Display the User results here -->
<div>
<%= Html.DisplayFor(x => x.FirstName) %>
</div>
<div>
<%= Html.DisplayFor(x => x.LastName) %>
</div>
<% } %>
</body>
</html>
現在您已經使用標準HTML技術實現了此功能,您可以通過引入AJAX來改進它:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<div align="center">
<% using (Ajax.BeginForm("SearchUser", "Search", null, new AjaxOptions { UpdateTargetId = "results" })) { %>
<table align="center">
<tr>
<td class="label">
Enter ID:
</td>
<td>
<input type="text" name="UserId" id="UserId" />
</td>
</tr>
<tr>
<td>
<button class="searchButton" id="searchButtong">Search</button>
</td>
</tr>
</table>
<% } %>
</div>
<hr />
<div id="result"></div>
<!-- TODO: Adjust with the proper version of jQuery that you are using -->
<script src="<%= Url.Content("~/Scripts/jquery-1.7.1.min.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js") %>" type="text/javascript"></script>
</body>
</html>
,然後讓你的控制器動作返回一個PartialView:
[HttpPost]
public ActionResult SearchUser(string UserId)
{
User user = ... go and fetch the user given the user id
// from wherever your users are stored (a database or something)
return PartialView(user);
}
,你需要定義(~/Views/Search/SearchUser.ascx
):
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<mVCaPPLICATION1.mODELS.uSER>"
%>
<!-- Display the User results here -->
<div>
<%= Html.DisplayFor(x => x.FirstName) %>
</div>
<div>
<%= Html.DisplayFor(x => x.LastName) %>
</div>
進入AJAX之前,我認爲這將是更好地讓OP熟悉自己用一些基本的HTTP協議原則,他目前丟失了恕我直言。 –
@DarinDimitrov同意,再次通讀問題後,我意識到OP沒有提到他想通過AJAX來做到這一點。不知道我從哪弄來的,肯定是那些讓我困惑的純HTML。 –
抱歉Christofer – Yusuf