Monday, 15 March 2010

c# - Custom TextBox Asp.net MVC Helper with wrapper -


I want to make my own text box helper which is a simple thing: input elements with some elements and labels Wrap, like:

  & lt; Div class = "col-xs-12" & gt; & Lt; Label & gt; Field Name & lt; / Label & gt; & Lt; Div & gt; & Lt; Input id = 'myId' name = 'MyName' type = 'text' value = 'myValue' & gt; & Lt; / Div & gt; & Lt; / Div & gt;  

In this view, I want to call it like this:

  @html Textbox ("name")  

How can I do this? Is there a way to call the base class in my assistant?


Update: Better solution

After Krishna's reply, I found a better approach to using code like this: {var baseFormat = htmlHelper} / p> < Pre> public static MvcHtmlString CliTextBoxFor & lt; TModeel, TProperty & gt; (This HtmlHelper & lt; TModeel & gt; HTMLHelper, expression & lt; function; TModeel, TProperty & gt; expression, string labeltext, text box (expression, format: empty, html content: HTML properties); var errors = htmlHelper ValidationMessageFor (expression, "", new {@class = "text-danger"}. ToString (); if (! String.IsNullOrEmpty (errors)) errors = "& lt; div & gt;" + Errors + "& Lt; / div & gt; "Var wrap = String.Format ("

"+" {2} "+" ", labeltext, baseform.tostening ( ), Returns;) Return the new MvcHtmlString;}

In this way, I am using TextBoxFor to create the original input element.

You need to create a custom HTML assistant for your text box as below.

  Namespace MvcApplication .Helpers {Public Static Class TextboxExtensions {Public Static HtmlString Custom Textbox (This HtmlHelper Assistant, String LabelName, NameValueCollection parameter) {var returnValue = string.Empty; If (parameters == incomplete) parameter. Count  current + (key + "=" + "'" + parameter [key] + "' '))); ReturnValue = String Format ("& lt; div class = 'col-xs-12' & gt; & lt; label & gt; {0} & lt; / label & gt;" + "& lt; div & gt; & lt; Input + Features + "& gt; & lt; / div & gt; & lt; / div & gt;", labelName); New HTML String Return (Return Value); }}}  

and to use the above extension method, follow these steps

In your MVC view, type the statement used at the top <

@ MvcApplication.using users

And, write the Html Assistant as

@ Html.CustomTextBox ("name" , New Name Value Collection {{"Id", "myId"}, {"value", "myValue"}})

Note: You can use json or something other than nameValueCollection Can be used.


No comments:

Post a Comment