1

I am trying to build a web site that lets user to create new violation.Each violation has its own input area.For instance, if user wants to create a new Ramp Width Violation, he/she should provide width or for Ramp Slope Violation slope should be provided as input.

Taking into account those requirements , I decided to have a dynamic property inside my view.

My dynamic object property can be boolean , integer or double according to violation type.

Here is my class that includes dynamic property.Other properties are removed for brevity.

public class CreateViolationViewModel
{

public string DynamicName { get; set; }

public object DynamicValue { get; set; }

}

Main View

 @Html.LabelFor(model => model.DynamicName, @Model.DynamicName, new { @class            = "control-label col-md-2" })
 <div class="col-md-10">
@Html.EditorFor(x => x.DynamicValue, "violationDynamics_" +  Model.DynamicValue.GetType().Name)
 </div>
@Html.HiddenFor(model => model.DynamicName, new {@value=Model.DynamicName })

EditorTemplate For Integer(violationDynamics_Int32.cshtml)

@{
    Layout = null;
}
@model int

@Html.TextBoxFor(x => x, new { @class = "form-control", @type = "number" })
@Html.Hidden("ModelType", Model.GetType())

EditorTemplate For Double(violationDynamics_Double.cshtml)

@{
    Layout = null;
}
@model double
@Html.TextBoxFor(x => x, new { @class = "form-control", @type = "number" })

@Html.Hidden("ModelType", Model.GetType())

Controller

   [HttpPost]
        public ActionResult Create(CreateViolationViewModel createViolationViewModel)
        {

        }

When the page is loaded it renders the related editor templates.The problem is that when the form is posted back dynamic value comes as a array of string as shown below.

Snapshot

I know I need something like model binder but haven't found the solution yet.By the way I take this approach from the previous answer here

So questions are ;

1- How can I make this approach work for post backs?

2- Is there any other recommend or easy approach to accomplish my task ?

Thanks

Community
  • 1
  • 1
erhan355
  • 806
  • 11
  • 23

0 Answers0