So I have a double field called Area. I print it this way:

<div>@Html.EditorFor(model => model.Area)</div>

My EditorTemplate for Double looks like this:

@{
    var attributes = this.ViewData.ModelMetadata.ContainerType.GetProperty(this.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(true);
    var htmlAttributes = GAtec.AgroWeb.Basic.Ux.Web.Helpers.EditorTemplateHelper.GetAllAttributes(ViewData, attributes);
    var decimalPlaces = htmlAttributes["data-format"].ToString().Split(',');

    var value = decimalPlaces.Length > 1 ? Model.ToString("n" + decimalPlaces[1]) : Model.ToString();

    @System.Web.Mvc.Html.InputExtensions.TextBox(this.Html, Html.NameFor(model => model).ToString(), value, htmlAttributes);
}

<script>
    $(document).ready(function () {
        $("#@Html.IdFor(model => model)").restrictNumber();
    });
</script>

Nice, but why the html element comes wrong as <input id="Area_Area" /> and the jQuery selector comes right as $("#Area") ?

Both NameFor and IdFor returns "Area" when I watch them on debbuging.

UPDATE:

My htmlAttributes(As @DarinDimitrov asked) returns this array:

["data-min": "0.0", "data-format": "0,2"]
有帮助吗?

解决方案 2

@System.Web.Mvc.Html.InputExtensions.TextBox(this.Html, "", value, htmlAttributes);

This resolved my problem. The point is, the MVC knows the model name so you don't have to say him what to print. If you do, it will concat with the model name. But why it does this, I really don't know.

其他提示

What's the point of stuffing gazilions of inline scripts inside your view (one for each editor template), when you could simply append a class="number" to your input field and then externalize your javascript in a separate file (which is where javascript belongs) and simply use a class selector:

$(document).ready(function () {
    $(".number").restrictNumber();
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top