MVC下拉列表提交至视图时为空问题求助
Hey Ryan, let's work through why your dropdown's value is coming up empty when you submit the form. This is a super common MVC pitfall, so here are the key checks and fixes to get it sorted:
1. Make Sure Your View Uses Correct Dropdown Binding
The most likely issue is how you're rendering the dropdown in your IncidentForm view. You need to explicitly bind it to the PersonInvolvedId property on your view model using DropDownListFor (not the generic DropDownList helper). Here's the correct syntax:
@model IncidentFormViewModel <!-- Other form fields --> <div class="form-group"> @Html.LabelFor(m => m.PersonInvolvedId) @Html.DropDownListFor( m => m.PersonInvolvedId, new SelectList(Model.People, "Guid", "FullName"), <!-- Replace "FullName" with your Person class's display property --> "Select a person involved", new { @class = "form-control" } ) @Html.ValidationMessageFor(m => m.PersonInvolvedId, "", new { @class = "text-danger" }) </div>
- Double-check that the
SelectListparameters match yourPersonclass: the second argument is the value field (Guid), and the third is the text field you want users to see (likeFullName,FirstName, etc.). - The empty "Select a person involved" option ensures users can't submit a default unselected value accidentally.
2. Verify Your POST Action is Set Up Correctly
You didn't share your POST controller code, but it needs to accept the IncidentFormViewModel as a parameter (not just the Incident object). Also, if validation fails, you must re-populate the People collection before returning the view—otherwise the dropdown will be empty:
[HttpPost] public ActionResult New(IncidentFormViewModel viewModel) { if (!ModelState.IsValid) { // Re-fetch people to repopulate the dropdown viewModel.People = unitofwork.Person.GetAll(); return View("IncidentForm", viewModel); } // Associate the selected person with the incident viewModel.Incident.PersonInvolvedId = viewModel.PersonInvolvedId; unitofwork.Incident.Add(viewModel.Incident); unitofwork.Complete(); return RedirectToAction("Index"); }
3. Confirm Model Binding is Working
- Check that your
Personclass'sGuidproperty is public with get/set accessors (it should be, but it's worth verifying). - Use your browser's dev tools (F12 → Network tab) to inspect the form data when you submit. Look for a field named
PersonInvolvedId—if it's missing, your dropdown isn't properly bound to the view model property.
4. Check for Validation Issues
Since PersonInvolvedId is a non-nullable Guid, MVC will mark it as required by default. If the user doesn't select an option, ModelState.IsValid will be false, and you'll need to show the validation message in your view (like the ValidationMessageFor line in the view example above).
内容的提问来源于stack exchange,提问作者Ryan Stuart

