Pass htmlAttributes to EditorFor template

1

Good morning!

I am working on templates for EditorFor for the different types of data, specifically int and double in order to generate them in text type, with a oninput that validates me not to enter incorrect information.

I started with the Int32 template and everything worked correctly, except that I can not find the return of how to get extra attributes

To be interpreted better;

The template (~ / Views / Shared / EditorTemplates / Int32.cshtml)

@model int?
@Html.TextBoxFor(model => model, null, new { @type = "text", @oninput = "this.value=this.value.replace(/[^0-9]/g,'')" })

When using it in a Vista , I get the desired result

@Html.EditorFor(x => x.CampoInt)

The problem is when I want to pass some extra attribute to EditorFor;

For example

@Html.EditorFor(x => x.CampoInt, new { htmlAttributes = new { @readonly = "readonly" } } )

The problem here is that both cases render the same thing.

<input oninput="this.value=this.value.replace(/[^0-9]/g,'')" type="text">

and what I intend, would be that in the second case, the following will be rendered

<input oninput="this.value=this.value.replace(/[^0-9]/g,'')" type="text" readonly="readonly">

I assume, that somehow I should receive a parameter within the Int32.cshtml template, but I've been looking for a while and can not find a solution, has anyone encountered a similar problem? p>

Thank you very much for the help!

    
asked by Juan Salvador Portugal 27.04.2018 в 14:12
source

2 answers

3

Solution

Thanks to an answer in the forum of stackoverflow in English , the solution was the following:

@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes);
    htmlAttributes.Add("oninput", "this.value=this.value.replace(/[^0-9]/g,'')";
}
@Html.TextBoxFor(model => model, htmlAttributes)

Thank you very much everyone for spending time reading the question! Greetings!

    
answered by 27.04.2018 / 18:09
source
1

Here is a solution. In your template Int32.cshtml:

@model int?

@{
    var actualData = new Dictionary<string, object> {
        { "type", "text"},
        { "oninput", "this.value=this.value.replace(/[^0-9]/g,'')"},
    };

    var viewData = ViewData["htmlAttributes"];
    if (viewData != null) {
        var type = viewData.GetType();
        var props = type.GetProperties();
        foreach (var prop in props) {
            actualData.Add(prop.Name, prop.GetValue(viewData));
        }
    }
}

@Html.TextBoxFor(model => model, null, actualData)

And how would you use it:

@Html.EditorFor(x => x.Cantidad)
@Html.EditorFor(x => x.Cantidad, new {htmlAttributes = new {@readonly = "readonly"}})

I hope I help you

    
answered by 27.04.2018 в 21:18