您已经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>