文章视图模型
public class ArticleViewModel : ViewModelBase
{
[Required(ErrorMessage = "Required")]
public string Title { get; set; }
[Required(ErrorMessage = "Choose the language")]
public BELocale Locale { get; set; }
}
public class BELocale : BEEntityBase
{
public string OriginalName { get; set; }
public string FriendlyName { get; set; }
public string TwoLetterISOName { get; set; }
}
视图“AddLocaleForArticle”
@model Models.ArticleViewModel
@using (Html.BeginForm("VefifyAddingLocaleForArticle", "Administration"))
{
@Html.TextBoxFor(m => m.Title, new { disabled = "disabled" })
@Html.DropDownListFor(m => m.Locale,
new SelectList(ViewBag.AvalaibleLocales, "ID", "OriginalName"), "Select a language"
)
@Html.ValidationMessageFor(m => m.Locale)
<input type="submit" value="Save" />
}
动作
public ActionResult VefifyAddingLocaleForPhoto(ArticleViewModel article)
{
//article.Locale == null for some reason.
//but article.Title isn't null, it contains the data
return RedirectToAction("AddingLocaleForPhotoSuccess", "adminka");
}
为什么article.Locale等于null以及如何修复它?
答案 0 :(得分:2)
提交表单时,下拉列表仅将所选值发送给控制器。因此,您不能指望它使用下拉列表填充整个复杂对象,例如BELocale
。最好的方法是填充其ID属性,并使用此ID从数据存储中获取剩余的对象。
所以你必须修改你的dropdownlist帮助器,以便它作为第一个参数绑定到locale的id属性:
@Html.DropDownListFor(
m => m.Locale.ID,
new SelectList(ViewBag.AvalaibleLocales, "ID", "OriginalName"),
"Select a language"
)
现在在相应的控制器操作中,您将获得id:
public ActionResult VefifyAddingLocaleForPhoto(ArticleViewModel article)
{
// article.Locale.ID will contain the selected locale id
// so you can use this information to fetch the corresponding BELocale object
...
}
答案 1 :(得分:0)
您可以在视图模型中填写此类下拉列表
public List<KeyValuePair<int, String>> locale
{
get
{
return _localerepo.Findlocals().Select(x => new KeyValuePair<int, string>(x.ID, x.OriginalName)).ToList();
}
}
在您的视图中使用此
<%:Html.DropDownListFor(x => x.ID, new SelectList(Model.locale, "key", "value"), "--Select locale--")%>
<%= Html.ValidationMessageFor(model => model.ID)%>