在 MVC2 中重构表单
我发现自己一遍又一遍地将这段代码粘贴到许多处理表单的视图上。 是否有一种简单的方法可以从 MVC2 中的视图重构以下标记? 唯一变化的部分是取消链接的路径(LocalizedSaveButton 和 LocalizedCancelLink 是我创建的辅助方法)。 我尝试将其提取到 PartialView 但失去了 BeginForm 功能。有什么建议吗?
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div class="span-14">
<% Html.EnableClientValidation(); %>
<%using (Html.BeginForm())
{%>
<fieldset>
<legend>Edit Profile</legend>
<%=Html.AntiForgeryToken() %>
<%=Html.EditorForModel() %>
<div class="span-6 prepend-3">
<%=Html.LocalizedSaveButton() %>
<%=Html.LocalizedCancelLink(RoutingHelper.HomeDefault()) %>
</div>
</fieldset>
<%}%>
</div>
I find myself pasting this code over and over on many views that deal with forms.
Is there a simple approach to refactor the following markup from a view in MVC2?
The only changing part is the route for the cancel link (LocalizedSaveButton and LocalizedCancelLink are helper methods I created).
I tried extracting it to a PartialView but I lose the BeginForm functionality. Any suggestions?
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div class="span-14">
<% Html.EnableClientValidation(); %>
<%using (Html.BeginForm())
{%>
<fieldset>
<legend>Edit Profile</legend>
<%=Html.AntiForgeryToken() %>
<%=Html.EditorForModel() %>
<div class="span-6 prepend-3">
<%=Html.LocalizedSaveButton() %>
<%=Html.LocalizedCancelLink(RoutingHelper.HomeDefault()) %>
</div>
</fieldset>
<%}%>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将代码包装在 HTML 扩展中,例如 BeginForm。从您的代码中在正确的位置调用 BeginForm。
您应该返回一个实现 IDisposable 的对象。在 dispose 中,您将存储结果的 Dispose 调用到 BeginForm。
您最终会得到:
技巧不是返回字符串或 MvcHtmlString,而是直接使用以下方式编写输出:
它会执行类似以下操作:
和扩展名:
免责声明:这是未经测试的代码。
You could wrap your code in an Html-Extension like the BeginForm. From your code call the BeginForm on the correct place.
You should return an object that implements IDisposable. In the dispose you call the Dispose of the stored result to BeginForm.
You end up with:
The trick is not to return a string or MvcHtmlString, but directly write the output using:
It would do something like:
and the extension:
Disclaimer: This is untested code.
这是我想出的:
它大部分有效,但我无法让 Html.EnableClientValidation() 与渲染的表单配合。
Here is what I came up with:
It mostly works but I haven't been able to get the Html.EnableClientValidation() to cooperate with the rendered form.