Hi @App Dev ,
I can't imagine what could have cause this to stop working
You can press F12 to see if there is any specific error message.
https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/hh968260(v=vs.85)
According to your description and code, you should want to implement DropDownList validation, so I wrote a related demo, you can refer to it.
Controller:
public class HomeController : Controller
{
private DistrictContext db = new DistrictContext();
public IList<SelectListItem> GetCountries()
{
var countries = db.Districts
.Select(x => new SelectListItem { Text = x.DistrictName, Value = x.DistrictId.ToString() })
.ToList();
countries.Insert(0, new SelectListItem { Text = "Choose a District", Value = "" });
return countries;
}
public ActionResult Index()
{
ViewBag.Districts = GetCountries();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(District district)
{
if (ModelState.IsValid)
{
ViewBag.Districts = GetCountries();
return RedirectToAction("Index");
}
else
{
try
{
ViewBag.Districts = GetCountries();
}
catch (Exception ex)
{
}
}
return View(district);
}
}
Model
public class District
{
[Required(ErrorMessage = "Required.")]
[Display(Name = "Employee District:")]
public int? DistrictId { get; set; }
[Display(Name = "Employee District:")]
public string DistrictName { get; set; }
}
cshtml
@默 WebApplication3.Models.District
@{
ViewBag.Title = "NWR";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<td>
<div class="editor-label">
@Html.LabelFor(model => model.DistrictId, "District")
</div>
</td>
<td>
<div class="editor-field">
@Html.DropDownListFor(model => model.DistrictId, new SelectList(ViewBag.Districts, "Value", "Text", new { @class = "form-control" }))
@Html.ValidationMessageFor(model => model.DistrictId)
</div>
</td>
<td><input type="submit" value="Submit" /></td>
}
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.