There is no ViewData item of type 'IEnumerable' that has the key 'GradingId'

前端 未结 3 1403
庸人自扰
庸人自扰 2020-12-22 08:33

Im trying to get a drop-down list to work for users who are being graded. Each user can have multiple gradings. So when i create a new grade i want a drop-down to specify

相关标签:
3条回答
  • 2020-12-22 09:06

    Although it's not part of your question, you're going to run into an entirely different problem once you get this operational. The name of your ViewBag item cannot be the same as the name of your property. Otherwise, the selected value will never be selected as the value in ViewBag will override the value on your model.

    Name your select list something like GradingIdChoices, not GradingId to disambiguate it.

    0 讨论(0)
  • 2020-12-22 09:20

    You can avoid issues like this by using a Viewmodel. Darin Dimitrov explains better than I do why you should use one.

    You get Intellisense and you can use the strongly typed versions of the Html helpers inside your views. You also get a refactor friendly code and no longer rely on magic strings. Also it is clear where the information is coming from to a given view by only looking at the view model that this view is strongly typed to.

    For your create page, an appropriate Viewmodel can be created;

    public class CreateGradeViewModel {
        Grading Grading { get; set; }
        IEnumerable<Grading> Gradings { get; set; }
    }
    

    Using that model for your view, you can then pass your dropdown collections as part of the model for the view. In this example, a domain object is included as part of the view model. If you require more control over this, you can use the properties of your domain model instead of a domain object, which would allow you to use data annotations. You would then need a mapper to map the object back to your domain type.

    All you need to change in your controller is the GET method to instantiate the model with your dropdown values, and the POST method to accept the view model and act on it accordingly.

    0 讨论(0)
  • 2020-12-22 09:31

    In Create get action you are not setting ViewBag.GradingId with the SelectList which is causing error in View:

    public ActionResult Create()
    {
            ViewBag.GradingId = new SelectList(db.Gradings, "GradingId", "CodeName");
            return View();
    }
    
    0 讨论(0)
提交回复
热议问题