Safely Reuse Editor Templates Across Different Types

77 views Asked by At

Suppose I have the following partial view for Decimal located at "~/Views/Shared/EditorTemplates/Decimal.cshtml":

@model decimal?
@{
    var attrs = ViewData;

    if (ViewData["type"] == null)
    {
        attrs.Add("type", "number");
    }
}

@Html.TextBoxFor(m => m, attrs)

I want to also use this template for properties of type Int32. So I create the following at "~/Views/Shared/EditorTemplates/Int32.cshtml":

@model int?
@Html.Partial("~/Views/Shared/EditorTemplates/Decimal.cshtml", (decimal?)Model)

Is there a better way to reuse editor templates? Are there any consequences to this pattern that I may have missed?

(Edit: added explicit cast from int to decimal?.)

1

There are 1 answers

2
Meysam Pourmonfared Azimi On

You can define an EditorTemplate as a whole. Once defining for both data types. For instance, you can use the following code samples:

Definition of EditorTemplate :

~/Views/Shared/EditorTemplates/Number.cshtml

Uassage of Helper in View :

@Html.EditorFor(model => model.SomeValue)

definition in ViewModel Class is

[UIHint("Number")]
public int SomeValue { get; set; }

OR

[UIHint("Number")]
public decimal SomeValue { get; set; }