ASP.NET MVC 中将数据从View传递到控制器中的表单提交法

本方法以搜索功能为例,在view中输入要搜索的关键字,提交到相应controller中进行处理。

view中代码:

<div class="searchBox">
@using (Html.BeginForm("Index", "Search"))
{
<div class="searchText">@Html.TextBox("searchKey")</div>
<input type="submit" value="" class="searchBtn" id="searchBtn" runat="server" />
}
</div>

运行后为:   

 

controller中代码:

 

 

MvcFirstWebEntities db = new MvcFirstWebEntities();

public ActionResult Index()
{
string key = Request.Form["searchKey"];
if (key.Trim() == "")
{
return Content("<script >alert('请输入要搜索的内容!');</script >", "text/html");

 

}
else
{
if (key.IndexOf("'") >= 0 || key.IndexOf("--") >= 0)
{
return Content("<script >alert('请勿输入非法字符!');</script >", "text/html");
}
else
{
var pro = (from ps in db.ProductInfoes where ps.productName.Contains(key) orderby ps.inDate descending select ps).ToList();
if (pro.Count() > 0)
{
StringBuilder proList = new StringBuilder();
foreach (var p in pro)
{
proList.Append("<li><a href=\"/Product/Details/" + p.ID + "/" + p.productType + "\">");
proList.Append("<div class=\"infoImg\"><img src=\"/Content/productImg/" + p.productPicTName + "\" /></div>");
proList.Append("<div class=\"infoName\">" + p.productName + "</div>");
proList.Append("</a></li>");
}
ViewData["proLists"] = proList.ToString();
}
else
ViewData["proLists"] = "没有匹配的内容!";
return View();
}
}

}

搞定!

 

 

posted @ 2014-04-25 10:10  一夜秋2014  Views(360)  Comments(0Edit  收藏  举报