Html.ActionLink超链接
输出超链接使用的HTML辅助方法是Html.ActionLink,常见的有以下3种写法:
@Html.ActionLink("超链接1","函数名称") @Html.ActionLink("超链接2","函数名称","控制器名称") @Html.ActionLink("超链接3","函数名称", new { userName = "admin", age = 12 })
Html.ActionLink示例
控制器
public ActionResult Index(string userName,int? age=2) { ViewBag.userName = userName; ViewBag.age = age; return View(); }
视图层
@Html.ActionLink("超链接1", "Index") <hr /> @Html.ActionLink("超链接2", "Index", "Test") <hr /> @Html.ActionLink("超链接3", "Index", new { userName = "admin", age = 12 }) <hr/> @ViewBag.userName <br/> @ViewBag.age
效果:
链接1、2直接访问,在url上可以看到,并且age的默认值是2,链接3显示admin与age的12,说明超链接符合预期。
HTML辅助方法生成表单
示例
控制器
[HttpPost] public ActionResult GetForm(string userName,string pwd,string sex,String []likes, string age,string introduce) { string info = ""; info += userName+"<br/>"; info += pwd + "<br/>"; info += sex + "<br/>"; foreach (string l in likes) { info += l + "<br/>"; } info += age + "<br/>"; info += introduce + "<br/>"; TempData["show"] = info; return Redirect("~/Test/Index"); }
视图层
@{ ViewBag.Title = "Index"; } <h2>超链接</h2> <hr /> <form action="~/Test/GetForm" method="post"> <fieldset> <legend>表单</legend> <hr /> <p> @Html.TextBox("userName", "", new { @placeholder = "请输入用户名" }) </p> <p> @Html.TextBox("pwd", "", new { @placeholder = "请输入用密码" }) </p> <p> @Html.RadioButton("sex", "男") 男 @Html.RadioButton("sex", "女") 女 </p> <p> @Html.CheckBox("likes", "0") 健身 @Html.CheckBox("likes", "1") 交友 @Html.CheckBox("likes", "2") 蹦迪 </p> <p> @Html.DropDownList("age", new List<SelectListItem> { new SelectListItem { Text = "22岁", Value = "22" } , new SelectListItem { Text = "23岁", Value = "23" } , new SelectListItem { Text = "24岁", Value = "24" } } , new { @class = "form-control" }) </p> <p> @Html.TextArea("introduce") </p> <p> <input type="submit" value="提交" class="btn btn-block btn-primary" /> </p> </fieldset> </form> <hr /> @TempData["show"]