I have a particularly interesting issue with a Razor Html Helper I'm trying to implement. The goal of this helper is to accept a System.Type, generate an JQuery-validate-able form from that Type's properties and associated attributes, as well as return a JavaScript string that will be used at runtime as validation rules for said generated form. I'm generating the form by calling @Html.Raw() repeatedly, building it as I iterate through properties and attributes. Originally, the html helper was written inside the only file that was going to use it, but because this is a generalized and often-used helper, I've moved it to the App_Code folder in my project.
This is the problem: I have discovered that ViewData is not available to me to return any data from the helper when this helper is in App_Code. Originally, I had two helpers; one to generate the form and squirrel away the JavaScript string in ViewData, and a second to take that same JavaScript string and print it into the document in my client-side script block. I want this helper to not only generate the form, but also give me this JavaScript string in one pass so don't have to do duplicate O(n) work.
Original pseudocode:
@helper MakeFormAndValidationRule(Type)
{
//generate form
//write form using @Html.Raw()
//generate validation rules simultaneously
//store validation rules in ViewData
}
@helper WriteValidationRules()
{
@Html.Raw(ViewData["rules"]);
}
<form>
MakeFormAndValidationRule(Type)
</form>
<script>
form.validate(@WriteValidationRules())
</script>
The question: what is the "best practice" for these sorts of cases? I could wr开发者_如何学Pythonite the validation rules into the DOM for later retrieval and pull it out using JQuery magic at run-time, but if there is a better, cleaner way to do this I'd like to know.
I think you want to create an extension method for the HtmlHelper class. I believe this should solve your issue with the ViewData issue.
The ViewData is part of the model, and you should use a custom HTML helper, not a Razor helper.
Something like this:
public static MvcHtmlString MakeFormAndValidationRule<TModel>(this HtmlHelper<TModel> helper, Type type)
{
var viewData = helper.ViewData;
// Your code...
}
More info on custom HTML helpers.
Also, i don't think you should be generating an entire form and validation with a helper. That is too much responsibility.
Instead consider segregating the responsibility to a custom editor template.
精彩评论