MVC3 - The model item passed into the dictionary is of type ERROR - asp.net-mvc-3

EDIT FOR SOLUTION:
The answer can be found here:
http://forums.asp.net/p/1794394/4941748.aspx/1?p=True&t=634704481730535356
BUT please see the below from Ricardo as well.
I've got a Controller/View called LedgerUser. I have a ViewModel called LedgerViewModel which contains an instance of LedgerUser and SelectList for instances of UserType and a property called UniqueId which i use for Images.
Now when i POST the form back from my Create View I get the following error:
The model item passed into the dictionary is of type 'Accounts.Models.LedgerUser', but this dictionary requires a model item of type 'Accounts.ViewModels.LedgerUserViewModel'.
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.InvalidOperationException: The model item passed into the dictionary is of type 'Accounts.Models.LedgerUser', but this dictionary requires a model item of type 'Accounts.ViewModels.LedgerUserViewModel'.
Now my understanding is that you pass the Model back to the Action Method and not the ViewModel? Im using the following technologies:
ASP.NET MVC3
Entity Framework 4 Database First
My code is:
LedgerUserViewModel:
/// <summary>
/// ViewModel to represent the LedgerUser & its required fields.
/// </summary>
public class LedgerUserViewModel
{
public SelectList UserTypes { get; set; }
public string UserType { get; set; }
public LedgerUser LedgerUser { get; set; }
public string UniqueKey { get; set; } //--Used for the Images.
public bool Thumbnail { get; set; }
}
I have extended the LedgerUser Model to decorate with Data Annotations:
[MetadataType(typeof(LedgerUserMetaData))]
public partial class LedgerUser
{
public class LedgerUserMetaData
{
[Required(ErrorMessage = "Date Of Birth Required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = " {0:dd/MM/yyyy}")]
[DataType(DataType.Date)]
public object DateOfBirth { get; set; }
}
}
My GET Action Method for LedgerUser:
// GET: /LedgerUser/Create
/// <summary>
/// Action Method to create the LedgerUser. Usually this will be once a user has registered
/// and will be directed from the AccountController.
/// </summary>
/// <param name="id">id</param>
/// <returns></returns>
public ActionResult Create(string id)
{
var uniqueKey = new Guid(id);
var userTypes = new SelectList(db.UserTypes, "id", "Description");
var ledgerUser = new LedgerUser()
{
id = uniqueKey,
RecordStatus = " ",
CreatedDate = DateTime.Now,
DateOfBirth = DateTime.Today
};
var viewModel = new LedgerUserViewModel()
{
UserTypes = userTypes,
LedgerUser = ledgerUser
};
return View(viewModel);
}
My POST Action Method for LedgerUser:
[HttpPost]
public ActionResult Create(bool Thumbnail,LedgerUser ledgeruser, HttpPostedFileBase imageLoad2)
{
///---code to do stuff..
}
My Create View:
#model Accounts.ViewModels.LedgerUserViewModel
#using Accounts.Models
#using (Html.BeginForm("Create", "LedgerUser", new { Thumbnail = true}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Ledger User</legend>
<div class="editor-field">
#Html.HiddenFor(model => model.LedgerUser.id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LedgerUser.AccountNumber,"Account Number")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LedgerUser.AccountNumber)
#Html.ValidationMessageFor(model => model.LedgerUser.AccountNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LedgerUser.FirstName,"First Name")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LedgerUser.FirstName)
#Html.ValidationMessageFor(model => model.LedgerUser.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LedgerUser.LastName,"Last Name")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LedgerUser.LastName)
#Html.ValidationMessageFor(model => model.LedgerUser.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LedgerUser.DateOfBirth,"D.O.B.")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LedgerUser.DateOfBirth)
#Html.ValidationMessageFor(model => model.LedgerUser.DateOfBirth)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LedgerUser.UserType, "User Type")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.LedgerUser.UserType,Model.UserTypes)
</div>
<div class="editor-label">
#Html.Label("Avatar")
</div>
<div class="editor-field">
#Html.UploadImageFor(model => model.UniqueKey,thumbnail:true)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Now i have interrogated the POST using Fiddler and i have found that name is correctly being set to "LedgerUser."
Content-Disposition: form-data; name="LedgerUser.id"
d1cd8e85-700d-4462-aa95-7428dbf58deb
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.AccountNumber"
1
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.FirstName"
Gareth
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.LastName"
Bradley
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.DateOfBirth"
12 April 2012
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.UserType"
b8502da9-3baa-4727-9143-49e33edc910c
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="imageLoad2"; filename="001.jpg" Content-Type:
image/jpeg
Im at a loss. Thanks guys

In your post action method for LedgerUser you are returning to the same view with an incorrect model, your code probably looks like this:
return View();
If you are returning to the same page after creating a new record, you need to make sure you do the same as in your get method:
var ledgerUser = new LedgerUser()
{
id = uniqueKey,
RecordStatus = " ",
CreatedDate = DateTime.Now,
DateOfBirth = DateTime.Today
};
var viewModel = new LedgerUserViewModel()
{
UserTypes = userTypes,
LedgerUser = ledgerUser
};
return View(viewModel);
If you don't want to do this, then just redirect after the post action method to another view such as (assuming you have an Index action):
return View("Index")
Better yet, IF you do need to post to the same view, then just use AJAX/jQuery post to call your Create action instead of the form post.
Good luck.

The error you're getting sounds like the error you'd receive if you passed the wrong type of viewmodel to your viewpage. Does your post method look like this?
[HttpPost]
public ActionResult Create(bool Thumbnail,LedgerUser ledgeruser, HttpPostedFileBase imageLoad2)
{
///---code to do stuff..
return View(ledgeruser);
}
If so, you're issue is that you're recreating the view with the wrong model type. That said, yes, you should be taking LedgerViewModel as your post parameter. With MVC, typically whatever model you passed into your view with your get, will be your parameter on the Post.
Suggested structure for your post. Uses the Post Redirect Get (PRG) pattern.
[HttpPost]
public ActionResult Create(LedgerViewModel model)
{
///---code to do stuff..
return RedirectToAction("Create", new {id = model.LedgerUser.id.ToString()});
}

Related

MVC3 Navigation Property Attributes and Client Side Validation

I am making my first tentative steps into MVC3 and have come across an issue with the translation of navigation properties within a model to a view. It seems that in the view navigational properties do not allow client side validation nor is the "Display" label attribute picked up.
I have the following simple model:
public class Entity
{
[Key,
ScaffoldColumn(false)]
public int Entity_Id { get; set; }
[Display(Name = "Entity Name"),
Required(ErrorMessage = "Please enter the entity name."),
StringLength(150, ErrorMessage = "Please ensure that the entity name is under 150 characters.")]
public string Entity_Nm { get; set; }
[Display(Name = "Entity Type"),
Required(ErrorMessage="Please select the entity type"),
ForeignKey("EntityType")]
public int EntityType_Id { get; set; }
public virtual EntityType EntityType { get; set; }
}
Which references this model:
public class EntityType
{
[Key]
public int EntityType_Id { get; set; }
[Display(Name = "Entity Name"), Required(ErrorMessage="Please enter the entity type name.")]
public string EntityType_Nm { get; set; }
}
When I create a controller with read/write actions and views for this model I get the following create form:
<fieldset>
<legend>Entity</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Entity_Nm)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Entity_Nm)
#Html.ValidationMessageFor(model => model.Entity_Nm)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EntityType_Id, "EntityType")
</div>
<div class="editor-field">
#Html.DropDownList("EntityType_Id", String.Empty)
#Html.ValidationMessageFor(model => model.EntityType_Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
This is fine apart from the label for the Entity Type drop down, for some reason it is not picking up the "Display" attribute of the navigation property within the model (note the lack of a space). Also client side validation is not enabled for the dropdown list (server side validation works without issue) despite decorating the property with a "Required" attribute. Client side validation works on the other fields. Please note that all the required .js script files have been included and I have also added the relevant enable validation keys to the web.config.
Any ideas what I am missing here? Thanks one and all.
for DropDownList Display issue just try below
#Html.LabelFor(model => model.EntityType_Id)

Performing create operations on two models via one action

I have two models : Category and Picture which refers to two tables, Categories and Pictures respectively. The Category model has a navigation property to Picture model.
Now, I created a controller using Scaffolding feature with CRUD operations for Category. Following is the code :-
public ActionResult Create()
{
ViewBag.ParentCategoryId = new SelectList(db.Categories, "Id", "Name");
ViewBag.PictureId = new SelectList(db.Pictures, "Id", "PictureUrl");
return View();
}
The automatically generated controller actions uses SelectList for listing the available Picture entries in the database and passes it down to dropdownlist for selection. This is not the ideal scenario since what I want is to unable the user to upload the Picture and then the reference is added to Category model. Later, the entries are saved to Categories and Pictures table.
Create model like this:
public class FullCategoryModel
{
public HttpPostedFileBase Picture { get; set; }
public Category CategoryModel {get; set;}
}
In view:
#using (Html.BeginForm("Create", "Category", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(model => model.Category.Name) // example, put there all category details
<input type="file" name="Picture" id="Picture" />
<input type="submit" value="Upload" />
}
Then create action:
[ActionName("Create")]
[HttpPost]
public ActionResult Create(FullCategoryModel model)
{
// here you can get image in bytes and save it in db,
// also all category detail are avalliable here
MemoryStream ms = new MemoryStream();
model.Picture.InputStream.CopyTo(ms);
Image picture = System.Drawing.Image.FromStream(ms);
// save in db as separate objects, than redirect
return RedirectToAction("Index", "Category");
}
First of all, I would like to thank #NickLarsen for making me believe that my understanding is good and i can achieve the task myself.
The problem was not that too tough but since i was new to Asp.net MVC, things were bit baffling. From the very start, I had the notion that i will be needing a ViewModel merging Category and Price classes and then a picture uploading API. But, somehow I wasn't able to fit the pieces in right place. Therefore after various regression and research over the internet, I achieved the task in following manner :-
First of all, I created a ViewModel
public class CatPicView
{
public Category Category { get; set; }
public Picture Picture { get; set; }
}
Second, I added the Uploadify javascript API
<script type="text/javascript">
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/uploadify/uploadify.swf")',
'script': '#Url.Action("Upload", "Category")',
'cancelImg': '#Url.Content("~/uploadify/cancel.png")',
'buttonText': 'Upload',
'folder': '#Url.Content("~/content/images")',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'auto': true,
'onComplete': function (event, ID, fileObj, response, data) {
var json = jQuery.parseJSON(response);
$("#pictureImage").html("<img src='"+json+"' alt='"+json+"' height='100px' width='100px'/>");
$("#Picture_PictureUrl").val(json);
$("#pictureRemove").show();
}
});
</script>
Hooked the API to following Server Function for renaming and saving to folder
[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData)
{
if (fileData != null && fileData.ContentLength > 0)
{
//var fileName = Server.MapPath("~/Content/Images/" + Path.GetFileName(fileData.FileName));
int pictureCount = 800000;
pictureCount += db.Pictures.Count();
string extension = Path.GetExtension(fileData.FileName);
string renamedImage = Server.MapPath("~/Content/Images/Categories/cat" + pictureCount + extension);
fileData.SaveAs(renamedImage);
return Json("/Content/Images/Categories/" + Path.GetFileName(renamedImage));
}
return Json(false);
}
And at last, rewrote the Category create Function as below for saving changes to DB
[HttpPost]
public ActionResult Create(CatPicView catPic)
{
if (ModelState.IsValid)
{
if (!String.IsNullOrEmpty(catPic.Picture.PictureUrl))
{
Picture picture = new Picture();
picture.PictureUrl = catPic.Picture.PictureUrl;
db.Pictures.Add(picture);
catPic.Category.PictureId = picture.Id;
}
db.Categories.Add(catPic.Category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
I think MVC scaffolding feature see the relation of two models as "Many to Many". That's why it created two drop down list for you. According to your scenario, you could do "Category" create page without "Picture" model data because "Picture" is the main entity here. So In the picture create action.
[HttpPost]
public ActionResult Create(Picture picture)
{
if (ModelState.IsValid)
{
databaseContext.Pictures.Add(picture);
databaseContext.SaveChanges();
return RedirectToAction("Index");
}
return View(picture);
}
In the view page of create picture
#model YourProjectName.Models.Picture
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Picture</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Url)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Url)
#Html.ValidationMessageFor(model => model.Url)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Categories.CategoryID, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryID", "Choose Category")
#Html.ValidationMessageFor(model => model.Categories.CategoryID)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

Issue with TryUpdateModel in MVC3

I have a problem with a TryUpdateModel in MVC3
When the Edit (post) is fired, I have the following code:
public ActionResult Edit(int id, FormCollection collection)
{
var review = FoodDB.FindByID(id);
if (TryUpdateModel(review))
return RedirectToAction("Index");
return View(review);
}
The view is built directly by the VS (so not changed by me)
If I trace the code, I see the new values in FormCollection, but after executing TryUpdateModel, it returns true, doesn't throw any error, but the review object isn't updated.
What could I do wrong?
EDIT
I come up with some more details:
First, the db is not real DB, but just a "simulation" - class with one static genric List
List<Review> Review;
Review class is simply a POCO, as below:
public class Review
{
public string Message { get; set; }
public DateTime Created { get; set; }
public int ID { get; set; }
public int Rating { get; set; }
}
The view is strong-typed, generated by VS from the Edit method of the controller. Fields are defined as below:
<div class="editor-label">
#Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)
</div>
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.Rating)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Rating)
#Html.ValidationMessageFor(model => model.Rating)
</div>
Call to var review = FoodDB.FindByID(id); returns Review object
Even if TryUpdateModel(review) does not work (I trace through code, and I inspected review object before and after the call, as well as the collection, and it receives correct values), yet the review obj is not updated.
However, I replaced it with my own hand-written method, as below, and in this case the review object DOES get updated:
private void MyTryUpdateModel(Review review, FormCollection collection)
{
review.Message = collection["Message"];
review.Rating = int.Parse(collection["Rating"]);
}
So the TryUpdateMethod SHOULD find proper fields in collection for updating, as I understand.
So, what can be wrong?
Thanks all
Based on the code you posted, the review object is not updated, because the new values in FormCollection have not been bound to your model. You are not using the DefaultModelBinder.
If your view is strongly typed (and assuming the type class is named Food), change your method signature and method as follows:
public ActionResult Edit(Food food)
{
if (ModelState.IsValid)
{
FoodDB.Update(food);
return RedirectToAction("Index");
}
return View(food);
}
The DefaultModelBinder will take the values from the form and bind them to your model.

Problem with Edit View using ViewModel

I have a complex object that I want to use in an edit view. To simplify things I have created a ViewModel and have successfully created the edit view page, and everything renders correctly. When I hit save, everything falls apart.
The ViewModel is as follows:
public class ClosureEditViewModel
{
public Model.Closure Closure { get; set; }
public Model.School School { get; set; }
public Model.ClosureDetail CurrentDetails { get; set; }
}
Some of the View is as follows:
<div class="display-label">School</div>
<div class="display-field">
#Html.DisplayFor(model => model.Closure.School.Name)
</div>
<div class="display-label">Closed</div>
<div class="display-field">
#Html.DisplayFor(model => model.Closure.Logged)
</div>
....
<div class="editor-label">
#Html.LabelFor(model => model.CurrentDetails.DateOpening, "Date Opening (dd/mm/yyyy)")
</div>
<div class="editor-field">
#Html.TextBox("DateOpening", Model.CurrentDetails.DateOpening.ToString("dd/MM/yyyy"))
#Html.ValidationMessageFor(model => model.CurrentDetails.DateOpening)
</div>
....
<tr>
<td>
#Html.CheckBoxFor(model => model.CurrentDetails.Nursery, (Model.School.Nursery ? null : new { #disabled = "disabled" }))
</td>
The important parts of the controller are as follows:
public ActionResult Edit(int id)
{
Data.IClosureReasonRepository reasonRepository = new Data.SqlServer.Repositories.ClosureReasonRepository(UnitOfWork);
IEnumerable<Model.ClosureReason> reasons = reasonRepository.GetAll();
Model.Closure closure = ClosureRepository.GetClosure(id);
Model.ClosureDetail currentDetail = closure.ClosureDetails.Last();
ViewModels.ClosureEditViewModel editClosure = new ViewModels.ClosureEditViewModel() { Closure = closure, School = closure.School, CurrentDetails = closure.ClosureDetails.Last() };
ViewBag.ReasonId = new SelectList(reasons, "Id", "Name", currentDetail.ReasonId);
return View(editClosure);
}
[HttpPost]
public ActionResult Edit(ViewModels.ClosureEditViewModel newDetail)
{
//if (ModelState.IsValid)
//{
//}
Data.IClosureReasonRepository reasonRepository = new Data.SqlServer.Repositories.ClosureReasonRepository(UnitOfWork);
IEnumerable<Model.ClosureReason> reasons = reasonRepository.GetAll();
ViewBag.ReasonId = new SelectList(reasons, "Id", "Name", newDetail.CurrentDetails.ReasonId);
return View(newDetail);
}
When I hit save the following message appears:
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 94: </td>
Line 95: <td>
Line 96: #Html.CheckBoxFor(model => model.CurrentDetails.P1, (Model.School.P1 ? null : new { #disabled = "disabled" }))
Line 97: </td>
Line 98: <td>
I just can't figure out why it is having problems with the School property but neither of the other two.
James :-)
It seems that Model.School is null when you render the view once again in the POST action. Make sure that it isn't null because in your view you don't have a single input field bound to the School property => this property will be null inside your POST controller action.
[HttpPost]
public ActionResult Edit(ClosureEditViewModel viewModel)
{
... some operations
// Make sure that viewModel.School is not null
// Remember that the checkbox is bound to CurrentDetails.P1 so
// when you post to this action there is nothing that will initialize
// the School property => you should do whatever you did in your GET
// action in order to initialize this property before returning the view
return View(viewModel);
}

UpdateModel not updating the model via ViewModel and property from DropDownListFor

I am trying to set up an Edit view on which I have a text box and DropDownListFor. I have figured out a way to populate the DDLF, and the rendered and posted values are correct, but i cant seem to get the model to update properly.
The object i am trying to update is generated from LINQtoSQL, and in database it has foreign key column. In LINQtoSQL class that resulted in "Contains" relationship. I can get to ID property that represents the column in DB, and also the object that it represents.
zupanija = new Zupanija(); //object that needs to be updated
zupanija.Drzava; //object that i want to change to make the update
zupanija.DrzavaID; //Property linked to object that should change
Only way i have figured out to do the update is to get the value from DDLF and use it to get the object that i want to change like this:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var zupanija = repo.ZupanijaById(id);
var drzava = new repoDrzava().DrzavaById(Convert.ToInt32(collection["Zupanija.DrzavaID"]));
zupanija.Drzava = drzava;
}
Also when i try to update the ID field like this, then i get the folowing error:
zupanija.DrzavaID = Convert.ToInt32(collection["Zupanija.DrzavaID"]);
Error: throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
This seems to me that it is very lousy way to do this, and i am trying to get UpdateModel to work.
I have found the solution while looking for something else, in blog by Joe Stevens:
Using Controller UpdateModel when using ViewModel
The catch is in following: When view model is used then to correctly bind the properties it is necessary to "instruct" the UpdateModel helper how to find the actual class we wish to update.
My solution required to modify
UpdateModel(zupanija); to UpdateModel(zupanija,"Zupanija");
Because i was using a ViewModel class that contained couple properties along with the main data class i wanted to update.
Here is the code, i hope it helps to understand:
public class ZupanijaFVM
{
public IEnumerable<SelectListItem> Drzave { get; private set; }
public Zupanija Zupanija { get; private set; }
...
}
// From Controller
//
// GET: /Admin/Zupanije/Edit/5
public ActionResult Edit(int id)
{
var zupanija = repo.ZupanijaById(id);
return zupanija == null ? View("Error") : View(new ZupanijaFVM(repo.ZupanijaById(id)));
}
//
// POST: /Admin/Zupanije/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var zupanija = repo.ZupanijaById(id);
if (TryUpdateModel(zupanija, "Zupanija"))
{
repo.Save();
return RedirectToAction("Details", new { id = zupanija.ZupanijaID });
}
return View(new ZupanijaFVM(zupanija));
}
//From View:
#model VozniRed.Areas.Admin.Models.ZupanijeFVM
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Zupanija</legend>
#Html.HiddenFor(model => model.Zupanija.ZupanijaID)
<div class="editor-label">
#Html.LabelFor(model => model.Zupanija.Naziv)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Zupanija.Naziv)
#Html.ValidationMessageFor(model => model.Zupanija.Naziv)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Zupanija.Drzava)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Zupanija.DrzavaID, Model.Drzave)
#Html.ValidationMessageFor(model => model.Zupanija.DrzavaID)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
A dropdown list is represented by a <select> tag in an HTML form. A <select> contains a list of <option> tags each containing an ID and a text. When the user selects an option and submits the form the corresponding ID of this options is POSTed to the server. And only the ID. So all you can expect to get in your Edit POST action is the ID of the selected option. And all that UpdateModel does is use the request parameters that are sent and convert them to a strongly typed object. But because all that is a POSTed is a simple ID that's all you can get. From there on you have to query the datastore using this ID if you want to obtain the corresponding model. So you cannot get something that is not existing.

Resources