Hi, I am trying to understand something a bit better with being new to C#, .NET 3.5 and MVC.
I am running through the MVC NerdDinner example and if you look at the ViewModel here: http://nerddinnerbook.s3.amazonaws.com/Part6.htm#highlighter_662935
You can see the Country list and how it gets populated, this seems to work fine but I tried to do a similar thing below using LINQ and I am having problems, with the SelectList approach even though it inherits from the IEnumerable interface.
I have got a task table with a foreign key to a status table. The below code gives me a NullReferenceException when I do a GET on a create action. I can see that an anonymous task object would not have a status set.. so I probably need to check for it, but I dont understand how this is not done for the NerdDinner example??
public class TaskViewModel {
// Properties
public Task Task { get; private set; }
public SelectList Status { get; private set; }
// Constructor
public TaskViewModel(Task task) {
TaskRepository taskRepo = new TaskRepository();
Task = task;
Status = new SelectList(taskRepo.GetStatus(), Task.Status.description);
}
}
//
// GET: /Tasks/Create
public ActionResult Create()
{
Task task = new Task();
return View(new TaskViewModel(task));
}
//Code from TaskRepository
private TaskManagerDataContext db = new TaskManagerDataContext();
public IQueryable<Status> GetStatus() {
return from status in db.Status
orderby status.description
select status;
}
I did another approach using LINQ for the type dropdown and the population of the drop down works but I am yet to test if it selects the correct value once a post is made and the details view is returned. I am also wondering whether this should some how be moved into my repository rather than have a class in my controller doing this sort of thing??
Here is the code:
//In TaskViewModel Class
public IEnumerable<SelectListItem> Types { get; private set; }
//In TaskViewModel constructor
IList<NPType> types = taskRepo.GetTypes().ToList();
Types =
from type in types
select new SelectListItem {
Selected = (type.typeId == task.typeId),
Text = type.description,
Value = type.typeId.ToString()
};
//The TaskForm partial View that is used for the Create action of the TaskController
<p>
<label for="type">type:</label>
<%= Html.DropDownList("Type", Model.Types)%>
<%= Html.ValidationMessage("type", "*") %>
</p>
<p>
<label for="status">status:</label>
<%= Html.DropDownList("Status", Model.Status)%>
<%= Html.ValidationMessage("status", "*") %>
</p>
and the TaskForm view inherits System.Web.Mvc.ViewUserControl