ASP.NET MVC 4 URL Routing + Overload Action Method + LINQ FirstOrDefault ( Handle Null ) 方法
/App_Start/RouteConfig.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcApplication { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); … … routes.MapRoute( name: "Home", url: "Home/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); … … } } } |
/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 Product(int? id) { entity = new BITestEntities(); if (id.HasValue) { var DataModel = entity.ProductEntities.Where(r => r.id == id).FirstOrDefault(); if (DataModel == null) DataModel = this.getDefaultNullValue(); return View(DataModel); } else { var DataModel = this.getDefaultNullValue(); return View(DataModel); } } … … private ProductEntity getDefaultNullValue() { ProductEntity DefaultNullValue = new ProductEntity(); DefaultNullValue.id = 0; DefaultNullValue.cat = “"; DefaultNullValue.subcat = “"; DefaultNullValue.model = “"; DefaultNullValue.price = 0; return DefaultNullValue; } } } |
/Home/Product ( /Views/Home/Product.cshtml ) |
<table width="100%" cellpadding="0" cellspacing="0"> <tr> <td><span>ID : </span></td> <td><span>@Model.id</span></td> </tr> <tr> <td><span>Category : </span></td> <td><span>@Model.cat</span></td> </tr> <tr> <td><span>Sub Category : </span></td> <td><span>@Model.subcat</span></td> </tr> <tr> <td><span>Model : </span></td> <td><span>@Model.model</span></td> </tr> <tr> <td><span>Price : </span></td> <td><span>$@Model.price</span></td> </tr> </table> |