FindControl 没有等效的 MVC,因为视图是在单个操作中构建的,其中 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);
}
}
用法
~/Views/Shared/_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> 标签,因此您不必为页面上的不同操作混合逻辑。