Didaxis
Didaxis

Reputation: 8736

ASP.NET MVC Forms for Model

I'm trying to learn MVC by building a full-featured website. I'm a little stuck when it comes to dealing with forms, and posting data, and models....

BTW: I'm using EF Code-First w/MS SQL CE

Here's the Models in question:

public class Assignment
{
    public int    AssignmentID   { get; set; }
    public int?   CourseID       { get; set; }
    public string Name           { get; set; }

   // etc...

    public virtual Course Course { get; set; }
}

public class Course
{
    public int CourseID { get; set; }

    // etc...
}

I'm loading a partial view that allows the user to add a new assignment

Controller:

public ActionResult Assignments()
{
    var assignments = myContext.Assignments.OrderBy(x => x.DueDate);
    return View(assignments);
}

[HttpPost]
public ActionResult AddAssignment(Assignment assignment)
{
    myContext.Assignments.Add(assignment);
    myContext.SaveChanges();

    return RedirectToAction("Assignments");
}

// Returns a strongly-typed, partial view (type is Assignment)
public ActionResult AddAssignmentForm()
{
    return PartialView();
}

Here's where I'm stuck: I want this form to have a drop down list for the different courses that an assignment could possibly belong to. For example, an assignment called "Chapter 3 Review, Questions 1-77" could belong to course "Pre-Algebra". However, if I use the code below, I have to explicitly declare the SelectListItems. I thought that with the given Assignment model above, I should be able to have the drop down list for Courses automatically generated using MVC awesomeness. What am I doing wrong?

AddAssignment Partial View:

@model MyModels.Assignment

@using(Html.BeginForm("AddAssignment", "Assignments"))
{
    // Can't I create a drop down list without explicitly
    // setting all of the SelectListItems?        

    @Html.DropDownListFor(x => x.Course, ....
}

Upvotes: 0

Views: 256

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

Basically you are confusing/mixing your business model and your UI model.

The quick fix here is to add the data for the dropdown list to the ViewBag (a dynamic object).

Alternatively you could create a class AssignmentModel that contains the relevant Assignment properties and the List.

And No, this is not well supported in the templates.

You do realize you'll need some error handling in the Post method(s)?

Upvotes: 1

Related Questions