没有MVC相当于为FindControl
,因为观点是建立在一个单一的操作,其中ASP.NET控件建立和修改在几个不同的事件。您无需查找控件,只需在构建时指定其所有属性即可。
大致相当于ASP.NET控件(至少在这种情况下)是HTML helper。 HTML助手实现为静态扩展方法,它允许在视图之间共享它们,并在加载视图时执行一些操作。
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class MyExtensions
{
public static MvcHtmlString TextBox1(this HtmlHelper helper, string name)
{
if (helper.ViewContext.HttpContext.Request.Path.ToUpper().Contains("/SAMPLE"))
{
return InputExtensions.TextBox(helper, name, null, new { @readonly = "readonly" });
}
return InputExtensions.TextBox(helper, name);
}
}
使用
〜/查看/共享/ _Layout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
</div>
<div class="float-right">
<section id="login">
@Html.Partial("_LoginPartial")
</section>
<nav>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</nav>
</div>
</div>
</header>
<div id="body">
@RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
@* Render custom HTML Helper *@
@Html.TextBox1("test")
@RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
注意的是,还可以直接把逻辑的观点,但你不能重用其他视图中的逻辑,它使你的视图看起来很混乱。
至于从文本框中读取数据,您需要将它放在<form>
标签内,以便将其发布到控制器操作方法,这与提交按钮单击事件大致相当。与ASP.NET不同,MVC支持多个<form>
标签,因此您不必在页面上混合用于不同操作的逻辑。
有没有办法在渲染时添加一个函数“如果Page = X然后将Textbox1设置为ReadOnly”? –
你可以使用[sections](http://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts-and-sections-with-razor)来这样做。您只需要覆盖每个适用视图的部分(当page = X时)。但是你给出的例子是当URL包含'/ sample'时禁用文本框,所以这就是我提供的答案。 – NightOwl888
该评论意味着不同的帖子。我马上删除它。你太棒了,不应该注意到它! –