pass a controller parameter to a view
What is the best way to passing a controller parameter to a view? The parameter is not related to any model, so cant do strongly typed view.
Controller:
public ActionResult DisplayParam(string id, string name)
{
return View();
}
View:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import NameSpace="System.IO" %> <开发者_JS百科%@ Import NameSpace="System" %> <%@ Import NameSpace="System.Data" %> <%@ Import NameSpace="System.Web" %> <%@ Import NameSpace="System.Text" %> <%@ Import Namespace="MY.Controllers" %>
Controller Parameter
<div>
Controller Parameter id: @id
Controller Parameter name: @name
</div>
The best way is to use a view model:
public class MyViewModel
{
public string Id { get; set; }
public string Name { get; set; }
}
and then have your controller action populate this view model and pass it to the view, just like this:
public ActionResult DisplayParam(string id, string name)
{
var model = new MyViewModel
{
Id = id,
Name = name
};
return View(name);
}
and finally you would have your view strongly typed to this view model and use the information to display it:
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.MyViewModel>"
%>
<div>
Controller Parameter id: <%= Html.DisplayFor(x => x.Id) %>
Controller Parameter name: <%= Html.DisplayFor(x => x.Name) %>
</div>
or if you were using the Razor view engine:
@model AppName.Models.MyViewModel
<div>
Controller Parameter id: @Html.DisplayFor(x => x.Id)
Controller Parameter name: @Html.DisplayFor(x => x.Name)
</div>
精彩评论