Question

I am trying to create a more "advanced" editor template for my MVC web application, but I am having a little bit of difficulty. Before I explain, let me show my source code.

Here is the code in my view (using the template):

@Html.EditorFor(model => model.Height, "UnitTemplate", new { unitModel = Model.HeightUnit, unitType = Units.Distance })

Here is the template:

@{
    Layout = null;
}
@using MyProject.Models;

@{
    var unitModel = this.ViewData["unitModel"];
    var unitType = this.ViewData["unitType"] as SelectList;
}

<div class="data-group">
    <div class="editor-label">
        @Html.LabelFor(model => model)
    </div>
    <div class="option1">
        @Html.TextBoxFor(model => model)
    </div>
    <div class="units">@Html.DropDownListFor(model => unitModel, unitType, new { @class = "unit" })</div>
    <div class="validation">
        <div>@Html.ValidationMessageFor(model => model)</div>
    </div>
</div>

As you can see, I have some value (in this case, Height) and I also have a unit type associated with that value (HeightUnit). I want to be able to GENERICALLY pass in the unit value associated with the model (since I am using this template in quite a number of places) as well as well as the type of unit (since this can also change). Ultimately, the goal is to allow the user to convert quickly between values.

Fortunately, everything works up to this point (conversion, population, etc), except that, when I save the results, the unitModel does NOT save to the database. Does anybody have suggestions for what I can do to get this to work?

Was it helpful?

Solution

You probably want to use an editor template for the entire model in this case as this template depends on multiple properties of the main view model (Height and HeightUnit):

@Html.EditorForModel("UnitTemplate")

and then in the ~/Views/Shared/EditorTemplates/UnitTemplate.cshtml editor template:

@using MyProject.Models;
@model MyViewModel
@{
    Layout = null;
}
<div class="data-group">
    <div class="editor-label">
        @Html.LabelFor(model => model.Height)
    </div>
    <div class="option1">
        @Html.TextBoxFor(model => model.Height)
    </div>
    <div class="units">
        @Html.DropDownListFor(
            model => model.HeightUnit, 
            Units.Distance, 
            new { @class = "unit" }
        )
    </div>
    <div class="validation">
        <div>
            @Html.ValidationMessageFor(model => model.Height)
        </div>
    </div>
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top