[英]Using TryUpdateModel with a Html.DropDownListFor
所以我正在嘗試使用TryUpDateModel
更新對象,問題出在下拉菜單上。
我有一個帶有圖像對象作為屬性的對象。
目前,我正在使用對象類作為模型,並從SelectListItems
列表中生成一個下拉列表,該列表的值設置為要設置為objects屬性的圖像的GUID。
我的查看代碼:
@Html.LabelFor(m => m.RibbonImage, "Ribbon Image:")
@Html.DropDownListFor(m => m.RibbonImage, (List<SelectListItem>)ViewBag.RibbonImages)
我在哪里生成列表:
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();
我在主對象類中的屬性:
/// <summary>
/// Gets or sets the ribbon image to use
/// </summary>
public virtual Image RibbonImage { get; set; }
我的動作方法:
[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.");
}
[..]
}
有沒有一種簡單的方法可以將DropDownListFor
與TryUpdateModel
一起使用,而不必手動更新每個屬性?
沒有完全理解您的問題。 但是,首先我想我將分享我們如何使用對我們來說很好的下拉列表控件。如果下面的代碼不能回答您的問題,希望更多地了解問題說明。
這通常是我在應用程序中使用下拉列表的方式。在表單發布中,包含SelectedCustomerId的父模型是通過已發布的(選定的)SelectedCustomerId構建的。默認的Model Binder綁定它沒有任何問題。
查看:
@model SampleDropDown.Models.CustomerData
using (Html.BeginForm("Continue", "Customer"))
{
if (Model.Customers != null)
{
@Html.DropDownListFor(m => m.SelectedCustomerId, new SelectList(Model.Customers, "CustomerId", "DisplayText"))
}
<input type="submit" value="Select" />
}
public class CustomerData
{
public List<Customer> Customers { get; set; }
public string SelectedCustomerId { get; set; }
public string Response { get; set; }
}
public class Customer
{
public string DisplayText { get; set; }
public string CustomerId { get; set; }
}
控制器:
[HttpPost]
public ActionResult Continue(CustomerData data)
{
return View("Index", data);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.