[英]Modify Html Helpers in ASP.NET MVC3 with razor
我有以下問題:
我想知道是否可以修改默認的html輔助方法,例如Html.BeginForm()方法。
我知道我可以編寫一個自定義幫助器方法,我可以添加一些東西,但其中一些有很多重載函數。
那么我唯一需要的是,你可以在渲染元素之后添加一些自定義的html字符串
例如:
@using(Html.BeginForm("setDate", "DateController", new { DateId = Model.Date.Identifier }, FormMethod.Post, new { id = "setDateForm" })) {
@* some input here... *@
}
之后
<form></form>
我想渲染驗證腳本,或其他東西,讓我們說jQuery驗證器:
<script>$('#setDateForm').validate();</script>
因為我不想一遍又一遍地這樣做(也許我可以忘記它一次..)修改默認的Html幫助器會很好。
如果不可能,我可能必須編寫自己的BeginForm或EndForm幫助程序的包裝器:/
作為一個非常基本的起點,你可以使用這樣的東西:
namespace YourProject.Helpers
{
public static class HtmlHelperExtensions
{
public static IDisposable CustomBeginForm(this HtmlHelper helper, string html)
{
return new MvcFormExtension(helper, html);
}
private class MvcFormExtension : IDisposable
{
private HtmlHelper helper;
private MvcForm form;
private string html;
public MvcFormExtension(HtmlHelper helper, string html)
{
this.helper = helper;
this.form = this.helper.BeginForm();
this.html = html;
}
public void Dispose()
{
form.EndForm();
helper.ViewContext.Writer.Write(this.html);
}
}
}
}
您需要在視圖中添加命名空間或將其添加到Views文件夾中的web.config文件中。 之后,您可以像這樣使用它:
@using (Html.CustomBeginForm("<p>test</p>")) {
// Additional markup here
}
這對我有用,但你肯定需要自定義它以滿足你的需要,特別是因為你可能想要將其他參數傳遞給Html.BeginForm()
。
您可以編寫自己的Extension方法來執行此操作。 從Codeplex獲取BeginForm方法的代碼。(MVC3源代碼是開源的 :))並對其進行相關更新以呈現您想要的表單。
該代碼在System.Web.MVC
項目下的FormExtensions.cs
類中提供。 查找從BeginForm Overrides調用的FormHelper方法。
這不可能。 你必須做自己的幫手。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.