本篇體驗自定義路由以及瞭解爲何須要自定義路由。css
準備html
□ View Modelspost
using System.Collections.Generic;
namespace MvcApplication2.Models
{
//單位
public class Unit
{
public int ID { get; set; }
public RentalProperty RentalProperty { get; set; }
public string Name { get; set; }
}
//屬性
public class RentalProperty
{
public int ID { get; set; }
public string Name { get; set; }
}
public class RentalPropertyTestData
{
public int ID { get; set; }
public List<RentalProperty> RentalProperties { get; set; }
public List<Unit> Units { get; set; }
}
}
□ 模擬一個數據層服務類this
using MvcApplication2.Models;
using System.Collections.Generic;
namespace MvcApplication2.Service
{
public class RentalService
{
public RentalPropertyTestData GetData()
{
List<RentalProperty> rps = new List<RentalProperty>();
RentalProperty rp1 = new RentalProperty() { ID = 1, Name = "長度" };
RentalProperty rp2 = new RentalProperty() { ID = 2, Name = "重量" };
rps.Add(rp1);
rps.Add(rp2);
List<Unit> units = new List<Unit>();
Unit unit1 = new Unit() { ID = 1, Name = "米", RentalProperty = rp1 };
Unit unit2 = new Unit() { ID = 2, Name = "公斤", RentalProperty = rp2 };
units.Add(unit1);
units.Add(unit2);
return new RentalPropertyTestData()
{
ID = 1,
RentalProperties = rps,
Units = units
};
}
}
}
RentalPropertiesControllerurl
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Ajax.Utilities;
using MvcApplication2.Models;
using MvcApplication2.Service;
namespace MvcApplication2.Controllers
{
public class RentalPropertiesController : Controller
{
RentalPropertyTestData _data = new RentalPropertyTestData();
public RentalPropertiesController()
{
RentalService s = new RentalService();
_data = s.GetData();
}
public ActionResult All()
{
return View(_data);
}
public ActionResult RentalProperty(string rentalPropertyName)
{
var rentalProperty = _data.RentalProperties.Where(a => a.Name == rentalPropertyName).FirstOrDefault();
return View(rentalProperty);
}
public ActionResult Unit(string rentalPropertyName, string unitName)
{
var unit = _data.Units.Find(u => u.Name == unitName && u.RentalProperty.Name == rentalPropertyName);
return View(unit);
}
}
}
視圖spa
□ All.csthml3d
展開
展開
□ Unit.cshtmlcode
展開
效果htm
All.csthmlblog
RentalProperty.cshtml
Unit.cshtml
路由改進目標
■ http://localhost:1368/RentalProperties/All 改進爲 ~/rentalproperties/
■ http://localhost:1368/RentalProperties/RentalProperty?rentalPropertyName=長度 改進爲 ~/rentalproperties/rentalPropertyName/
■ http://localhost:1368/RentalProperties/Unit?rentalPropertyName=長度&unitName=米 改進爲 ~/rentalproperties/rentalPropertyNam/units/unitName
添加自定義路由規則
展開
http://localhost:1368/RentalProperties
http://localhost:1368/RentalProperties/長度
http://localhost:1368/RentalProperties/長度/Units/米
□ 參考博文