【问题标题】:Using TryUpdateModel with a Html.DropDownListFor将 TryUpdateModel 与 Html.DropDownListFor 一起使用
【发布时间】:2012-08-13 09:50:00
【问题描述】:

所以我正在尝试使用TryUpDateModel 更新对象,问题出在下拉列表中。

我有一个带有图像对象作为属性的对象。

目前我正在使用 objects 类作为模型,并从 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.");
    }

    [..]
}

有没有一种简单的方法可以将DropDownListForTryUpdateModel 一起使用,而不必手动更新每个属性?

【问题讨论】:

  • 如果有助于了解图像类是什么样的,我也可以发布。

标签: c# asp.net-mvc asp.net-mvc-3 model-view-controller


【解决方案1】:

没有完全理解你的问题。但是首先,我想我会分享我们如何使用对我们来说很好的下拉列表控件。如果下面的代码不能回答你的问题,想了解更多关于问题陈述的信息。

这通常是我在我们的应用程序中使用下拉列表的方式。在我们的表单发布中,包含 SelectedCustomerId 的父模型构建了发布的(选定的)SelectedCustomerId。默认的模型绑定器将其绑定没有任何问题。

查看:

@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);
    }

【讨论】:

  • 其实这或多或少是我想出的解决方案。通过使用 @Html.DropDownListFor(m =&gt; m.RibbonImage.Id[...]) 一切正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多