mslugx mslugx - 1 month ago 8
jQuery Question

How to return text input value instead of dropdown list item when certain dropdown value is selected for model binding?

All, I am playing around with ASP.net CORE. I am trying to find out the best practice in normal situation. The Razor code below is generating a dropdow in HTML. Whenever users choose "Other" in the list, it's going to fire off the jquery code and append an input text field after the dropdown. My question is how can i get the form to do a HTTP post using input text field instead of the dropdown value? Thanks in advance.

<div class="form-inline" >

<select name="Genre" class="form-control form-inline" id="genreselect" >
@foreach (var item in Model)
{
<option>@item</option>
}
<option>Other</option>
</select>
</div>


jQuery Code:

$("#genreselect").change(function () {
//$("#genreinput").show();
if ($("#genreselect option:selected").val() === 'Other') {
//$('#genreselect').replaceWith('<input type="text" name="state_d" id="state_d">');
$(this).after('<input id="genreinput" class="form-control" type="text" name="Genre" />');
//$(this).
//$("#genreinput").show();
}
else {
$("#genreinput").hide();

}
});

Answer

Use a different name for the text input like OtherGenre and add a property with that name to your view model.

<input id="OtherGenre" class="form-control" type="text" name="OtherGenre" />

public class MyViewModel
{
    public string Genre {get; set;}
    public string OtherGenre {get; set;}
}

Then in your server side logic if the Genre is "Other" take the value from the new property (You could do this when saving the record or when you need to display it later on):

//Either overwrite Genre before saving it
public ActionResult MyPostAction(MyViewModel model)
{
    if(model.Genre == "Other") model.Genre=model.OtherGenre;

    // ...save model ...
}

//Or apply that logic when displaying it
<span>@(@Model.Genre=="Other" ? Model.OtherGenre : Model.Genre)</span>
Comments