Im en utilisant un MODELVIEW afin de créer un DropDownList:DropDownListFor Référence d'objet non définie à une instance d'un objet
MODELVIEW
public class CreateSubjectModel
{
public Subject Subject { get; set; }
public IEnumerable<SelectListItem> Careers { get; set; }
}
L'action [HttpGet]
public ActionResult Create()
{
CreateSubjectModel model = new CreateSubjectModel();
List<SelectListItem> careerList = new List<SelectListItem>();
foreach (var career in _careerManager.GetCareers())
careerList.Add(new SelectListItem() { Text = career.Institution + " - " + career.Name, Value = career.id.ToString() });
model.Careers = careerList;
return View(model);
}
Le Action [HttpPost]
public ActionResult Create(CreateSubjectModel createSubjectModel)
{
try
{
_subjectManager.SaveSubject(createSubjectModel.Subject);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Et la vue:
<div class="editor-field">
@Html.DropDownListFor(model => model.Careers, Model.Careers)
@Html.ValidationMessageFor(model => model.Careers)
</div>
Le problème est que quand je frappe Submit J'ai ce problème:
**Object reference not set to an instance of an object.**
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 47: </div>
Line 48: <div class="editor-field">
Line 49: @Html.DropDownListFor(model => model.Careers, Model.Careers)
Line 50: @Html.ValidationMessageFor(model => model.Careers)
Line 51: </div>
Je regarde partout et je ne peux pas trouver un exemple de travail ou d'un tutoriel qui me aide. Espérons que vous pouvez faire ...
_Ne pas avaler toutes les exceptions_ – SLaks
Les exceptions peuvent, en effet, être de délicieuses friandises, mais vous devriez au moins * les regarder * avant de les avaler entières. –
Copie possible de [Qu'est-ce qu'une exception NullReferenceException, et comment la réparer?] (Http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –