I have an entity “ProgramType” exists in a drop down list when editing the model. If the user doesn’t see what they need in the existing collection, they need to have the ability to add a new entry to that collection on the same editing screen.
Essentially, it seems like I need the same entity to exist twice in the same edit view. If a particular value is selected for the drop down menu, then a text field does a jQuery “show” to allow them to add new data.
<div class="editor-label">
@Html.LabelFor(model => model.ProgramTypeId, "Program Type")
</div>
<div class="editor-field">
@Html.DropDownList("ProgramTypeId", "- Select a Program Type - ")
@Html.ValidationMessageFor(model => model.ProgramTypeId)
</div>
//this div is hidden via jQuery unless needed
<div class="editor-label hiddenDiv">
@Html.Label("New Program Type Title:")
</div>
<div class="editor-field hiddenDiv">
@Html.EditorFor(model => model.ProgramType.ProgramType)
@Html.ValidationMessageFor(model => model.ProgramType.ProgramType)
</div>
//
<div class="editor-label">
@Html.LabelFor(model => model.ProgramYear)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProgramYear)
@Html.ValidationMessageFor(model => model.ProgramYear)
</div>
What is the best way to achieve this? I’m really tempted to just use the form collection, but that seems like it might be “poor practice”.
public class SurveyProgramModel
{
[Key]
public int ProgramId { get; set; }
[DisplayName("Year")]
public int ProgramYear { get; set; }
[DisplayName("Status")]
public int ProgramStatusId { get; set; }
[DisplayName("Program Title")]
public string ProgramTitle { get; set; }
public int ProgramTypeId { get; set; }
[DisplayName("Program Type")]
public virtual SurveyProgramTypeModel ProgramType { get; set; }
[DisplayName("Status")]
public virtual ProgramStatusModel ProgramStatusModel { get; set; }
public virtual ICollection<SurveyResponseModel> SurveyResponseModels { get; set; }
}
public class SurveyProgramTypeModel
{
[Key]
public int ProgramTypeId { get; set; }
[DisplayName("Program Type")]
public string ProgramType { get; set; }
}
One approach would be to modify your view model to contain e.g.
In your controller action, populate ProgramTypes with the list of possible values from your persistence layer, plus an extra value of “Add new…”.
In your view you can then render your dropdown as
Then add some jQuery to show and hide a
<div>based on the selected value. Inside this<div>addAnd in your
[HttpPost]action method add logic to determine if they are adding a new value then save the new value to your persistence layer.