繁体   English   中英

将TryUpdateModel与Html.DropDownListFor一起使用

[英]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.");
    }

    [..]
}

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

没有完全理解您的问题。 但是,首先我想我将分享我们如何使用对我们来说很好的下拉列表控件。如果下面的代码不能回答您的问题,希望更多地了解问题说明。

这通常是我在应用程序中使用下拉列表的方式。在表单发布中,包含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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM