0

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, ....
}
1
  • 3
    I think you overestimate the awesomeness. Commented Nov 21, 2011 at 14:42

1 Answer 1

1

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)?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, the example code I posted is just the bare minimum to Illustrate my question. What do you mean by, "not well supported in the templates"?
It won't generate stuff for what's in the ViewBag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.