ASP.NET MVC 4 Controller + View ( Razor ) + DropDownList + Cross Action Form Post + Form Collection 使用方法
/Home/Form ( /Views/Home/Form.cshtml ) |
<table> @using (@Html.BeginForm("FormResult", "Home")) { <tr> <td>Category :</td> <td>@Html.DropDownList("Category", (SelectList)ViewBag.Category)</td> </tr> <tr> <td colspan="2"> <input type="submit" name="Submit" value="Submit" /> </td> </tr> } </table> |
/Home/FormResult ( /Views/Home/FormResult.cshtml ) |
<table class="product_tbl" cellpadding="10" cellspacing="0"> @foreach (var product in Model) { <tr> <td><span class="transaction_cell">@product.cat</span></td> <td><span class="transaction_cell">@product.subcat</span></td> <td><span class="transaction_cell">@product.model</span></td> <td><span class="transaction_cell">@product.price</span></td> </tr> } </table> |
/Controller/HomeController.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication.Controllers { public class HomeController : Controller { BITestEntities entity; … … public ActionResult Form() { entity = new BITestEntities(); var DataModel = (from Product in entity.ProductEntities select new { Product.cat }).Distinct().ToList(); ViewBag.Category = new SelectList(DataModel, "cat", "cat"); return View(DataModel); } public ActionResult FormResult(FormCollection collection) { entity = new BITestEntities(); String Category = collection["Category"]; if (Category != null) { var DataModel = entity.ProductEntities.Where(r => r.cat == Category).ToList(); return View(DataModel); } else { var DataModel = entity.ProductEntities.ToList(); return View(DataModel); } } } } |