An article view model
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; }
}
A view “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" />
}
An action
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");
}
Why article.Locale is equal null and how to fix it?
When the form is submitted a dropdown list sends only the selected value to the controller. So you cannot expect it to populate an entire complex object such as
BELocaleusing a dropdownlist. The best you could is to populate its ID property and fetch the remaining of the object from your data store using this id.So you will have to modify your dropdownlist helper so that it is bound to the id property of the locale as first argument:
Now inside the corresponding controller action you will get the id: