So I’m trying to update an object using TryUpDateModel, the problem is with dropdowns.
I have an object with an image object as a property.
Currently I am using the objects class as the model, and generating a dropdown from a list of SelectListItems that has values set to the guid of the image I’d like to set to the objects property.
My view code:
@Html.LabelFor(m => m.RibbonImage, "Ribbon Image:")
@Html.DropDownListFor(m => m.RibbonImage, (List<SelectListItem>)ViewBag.RibbonImages)
Where I generate the list:
ViewBag.RibbonImages = this.Datastore.GetAll<Image>()
.Where(x => x.Type == ImageType.Ribbon)
.Select(x => new SelectListItem()
{
Text = x.Description + " \u2013 " + Path.GetFileName(x.Filename),
Value = x.Id.ToString()
})
.ToList();
My property in the main object class:
/// <summary>
/// Gets or sets the ribbon image to use
/// </summary>
public virtual Image RibbonImage { get; set; }
My action method:
[HttpPost]
[..]
public ActionResult Update(Guid? id)
{
RibbonLookup ribbon = this.Datastore.Query<RibbonLookup>().SingleOrDefault(x => x.Id == id);
[..]
string[] properties = new string[]
{
"RibbonImage"
};
if (this.TryUpdateModel<RibbonLookup>(ribbon, properties))
{
this.Datastore.Update<RibbonLookup>(ribbon);
ModelState.AddModelError(string.Empty, "The ribbon has been updated.");
}
else
{
ModelState.AddModelError(string.Empty, "The ribbon could not be updated.");
}
[..]
}
Is there a simple way to use a DropDownListFor with TryUpdateModel instead of having to update each property manually?
Did not completely understand your question. However to start with, thought I will share how we use the dropdown list control which works fine for us.IF the below code doesn’t answer your question, would like to know more about the problem statement.
This is usually how i use Drop-down list in our application.On our Form Post the Parent Model that contains the SelectedCustomerId is builtth the posted(selected) SelectedCustomerId.The default Model Binder binds it without any issues.
View :
Controller :