[英]Textbox Validation Works according to dropdown value
我有一個下拉菜單,其中有3個可用選項:
我希望如果用戶選擇“其他”選項,則注釋文本框為必填項,否則注釋文本框不是必填項,
這是我在View模型中的驗證代碼
[Required(ErrorMessage="Please Enter Comment")]
public string Comment { get; set; }
這是我的下拉菜單和驗證代碼
@Html.DropDownList("Reason", new List<SelectListItem>()
{
new SelectListItem() { Text= "Event Cancelled", Value = "Cancelled" },
new SelectListItem() { Text= "Event PostPoned", Value = "PostPoned" },
new SelectListItem() { Text= "Other", Value = "Other" }
}, "--Select Cancellation Reason --", new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.Reason, "", new { @class = "text-danger" })
僅當選擇其他時,如何使評論變為強制性?
您可以在post方法中進行此操作(如果需要)
Public ActionResult AssumeThisAsYourPostMethod(YourModel modelObject)
{
if(modelObject.Reason=="Other" && String.IsNullOrEmpty(modelObject.Comment) )
{
ModelState.AddModelError("Comment","Your Validation Message");
return View("YourViewName");
}
}
在更改事件上使用jQuery,如果select的值為“ Other”,則將必需的屬性添加到注釋框。
$("body").on('change', "#Reason", function () {
var Reason= $(this).val().trim() ;
if (Reason == 'Other')
{
$("input[name = Comment]").prop('required',true);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.