![](/img/trans.png)
[英]Want to pass data from the controller to the view WITHOUT adding it to the URL
[英]How to pass data to controller's field from URL?
我知道如何將數據作為參數從URL發送到控制器的操作方法。 在這里,我想知道如何將數據從URL發送到控制器的字段?
public MyAwesomeController : Controller {
public string SectionCode { get;set; }
}
然后定義Routes:
routes.MapRoute(
name : "AwesomeRouter",
url : "{code}/{action}",
defaults: new {controller = "MyAwesome", action = "Index", /* What to do here?*/}
);
我想用URL中的{code}填充SectionCode。 有可能實現嗎?
是的,您可以從Controller的基本類創建繼承的類,並重寫OnActionExecuting方法,在該方法中,您可以讀取url,路由或任何表單數據並將其存儲在會話中,或直接填寫您需要的任何字段。 然后創建您的控制器的繼承類。
public class MyAwesomeController : MyControllerBase
{
public ActionResult Index()
{
//this.SectionCode is available populated here
return View();
}
}
public class MyControllerBase : Controller
{
public string SectionCode
{
get;
private set;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
this.SectionCode = filterContext.RequestContext.RouteData.Values["code"].ToString();
base.OnActionExecuting(filterContext);
}
}
每次您使用提供的路由定義在此控制器中執行任何操作時,都會自動填充該字段。 但是,當您定義了多個路徑時,它們很容易陷入沖突,例如。 代碼何時將與任何控制器名稱匹配。 普通網站不應以這種方式工作。
您的路線應如下所示:
routes.MapRoute(
name: "AwesomeRouter",
url: "{code}/{action}",
defaults: new { controller = "MyAwesome", action = "Index" }
);
然后,應將代碼作為參數傳遞給操作。 我將其存儲在查看包中,以進行說明:
public class MyAwesomeController : Controller
{
public ActionResult Index(string code)
{
ViewBag.Code = code;
return View();
}
}
然后使用此URL:
http://somehost/4567/Index
如果您在視圖中訪問Viewbag屬性:
@ViewBag.Code
您應該看到:
4567
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.