如果为模型绑定选择了某个下拉列值,如何返回文本输入值而不是下拉列表项?

时间:2016-10-06 01:38:30

标签: jquery html razor asp.net-core tag-helpers

所有,我正在玩ASP.net CORE。我想在正常情况下找出最佳做法。下面的Razor代码正在生成HTML格式的下拉列表。每当用户选择"其他"在列表中,它将触发jquery代码并在下拉列表后附加一个输入文本字段。我的问题是如何使用输入文本字段而不是下拉值来获取表单来进行HTTP发布?提前谢谢。

<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代码:

$("#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();

    }
});

1 个答案:

答案 0 :(得分:0)

OtherGenre等文本输入使用其他名称,并将具有该名称的属性添加到视图模型中。

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

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

然后在服务器端逻辑中,如果类型为“其他”,则从新属性中获取值(您可以在保存记录时或以后需要显示时执行此操作):

//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>
相关问题