当为模型绑定选择了某个下拉值时,如何return文本输入值而不是下拉列表项?
How to return text input value instead of dropdown list item when certain dropdown value is selected for model binding?
所有,我正在玩ASP.net CORE。我试图找出正常情况下的最佳做法。下面的 Razor 代码在 HTML 中生成一个下拉菜单。每当用户在列表中选择 "Other" 时,它将触发 jquery 代码并在下拉列表后附加一个输入文本字段。我的问题是如何让表单使用输入文本字段而不是下拉值来执行 HTTP post?提前致谢。
<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();
}
});
为文本输入使用不同的名称,例如 OtherGenre
,并将具有该名称的 属性 添加到您的视图模型。
<input id="OtherGenre" class="form-control" type="text" name="OtherGenre" />
public class MyViewModel
{
public string Genre {get; set;}
public string OtherGenre {get; set;}
}
然后在您的服务器端逻辑中,如果流派是 "Other",则从新的 属性 中获取值(您可以在保存记录或稍后需要显示时执行此操作) :
//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>
所有,我正在玩ASP.net CORE。我试图找出正常情况下的最佳做法。下面的 Razor 代码在 HTML 中生成一个下拉菜单。每当用户在列表中选择 "Other" 时,它将触发 jquery 代码并在下拉列表后附加一个输入文本字段。我的问题是如何让表单使用输入文本字段而不是下拉值来执行 HTTP post?提前致谢。
<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();
}
});
为文本输入使用不同的名称,例如 OtherGenre
,并将具有该名称的 属性 添加到您的视图模型。
<input id="OtherGenre" class="form-control" type="text" name="OtherGenre" />
public class MyViewModel
{
public string Genre {get; set;}
public string OtherGenre {get; set;}
}
然后在您的服务器端逻辑中,如果流派是 "Other",则从新的 属性 中获取值(您可以在保存记录或稍后需要显示时执行此操作) :
//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>