if the user selects "Fresher" from the dropdown, and if he doesn't enter any value in Company detail. it should give a alert message.
what is the javascript condtion to get the alert message ?
any help is appriciable. Thanks
The razor code is :
<div class="form-group">
<label>Current Status</label><span class="text text-danger">*</span> @Html.DropDownList("employmentStatus", new SelectList(new Dictionary
<int, string> { { 0, "Current Status" }, { 1, "Fresher" }, { 2, "Employed" }, { 3, "Un-Employed" } }, "Key", "Value"), new { @class = "form-control", @id = "employmentStatus" }) @Html.ValidationMessageFor(model => model.employmentStatus, "", new { @class = "text-danger"
})
</div>
<div class="form-group">
<label>Company Detail</label><span class="text text-danger">*</span> @Html.EditorFor(model => model.currentCompany, new { htmlAttributes = new { @class = "form-control",@id= "currentCompany" } }) @Html.ValidationMessageFor(model => model.currentCompany,
"", new { @class = "text-danger" })
</div>
The javascript code is :
if ($("#employmentStatus").val() == "Fresher" || ("#employmentStatus").val() == "Employed" && ("#currentCompany").val() == "" || ("#currentCompany").val() == null) {
alert('Please select Current Company Name')
return false;
}
Assumption:
You have a button or form event that firing onSubmit method before posting data to API.
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { @id = "form" }))
{
// Form inputs
<input type="submit" value="Submit" onclick="return onSubmit()" class="btn btn-primary">
}
Since you specify the <option> value as Dictionary key, while label text as Dictionary value.
@Html.DropDownList("employmentStatus",
new SelectList(new Dictionary<int, string>
{
{ 0, "Current Status" },
{ 1, "Fresher" },
{ 2, "Employed" },
{ 3, "Un-Employed" }
}, "Key", "Value"),
new { @class = "form-control", @id = "employmentStatus" })
Rendered HTML
<select class="form-control" id="employmentStatus" name="employmentStatus">
<option value="0">Current Status</option>
<option value="1">Fresher</option>
<option value="2">Employed</option>
<option value="3">Un-Employed</option>
</select>
Hence, you need to check the selected option's value with Dictionary key and currentCompany input element cannot be empty string or null.
if ($("#employmentStatus").val() == "1"
&& ($("#currentCompany").val() == "" || $("#currentCompany").val() == null)) {
alert('Please select Current Company Name');
return false;
}
OR
if ($("#employmentStatus option:selected")[0].text == "Fresher"
&& ($("#currentCompany").val() == "" || $("#currentCompany").val() == null)) {
alert('Please select Current Company Name');
return false;
}