I'm trying to create a RoomType record. Each RoomType have a collection of RoomTypeInfos, which are descriptions for every Language. Then, each RoomTypeInfo is associated to a Language record.
So to create a RoomType, I preload the object with one RoomTypeInfo for each Language.
Get action:
//
// GET: /RoomType/Create/IdHotel
[HttpGet]
public ActionResult Create(int id)
{
List<Language> _Languages = __roomTypeRepository.GetLanguages().ToList<Language>();
RoomType roomType = new RoomType { IdHotel = id };
roomType.RoomTypeInfos = new System.Data.Linq.EntitySet<RoomTypeInfo>();
foreach (Language Language in _Languages)
{
roomType.RoomTypeInfos.Add(new RoomTypeInfo { Language = Language });
}
return View(roomType);
}
Post action:
//
// POST: /RoomType/Create/
[HttpPost]
public ActionResult Create(RoomType roomType)
{
try
{
if (ModelState.IsValid)
{
__roomTypeRepository.InsertRoomType(roomType);
return RedirectToAction("Index", new { id = roomType.IdHotel });
}
else
{
return View(roomType);
}
}
catch
{
return View(roomType);
}
}
So if in the post action the model is not valid or an exception is caught, I get an error in @Model.Language.Name at the view, because Language is now null.
Code for the RoomTypeInfo editor template:
@model DataAccess.RoomTypeInfo
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.IdRoomType)
@Html.HiddenFor(model => model.IdLanguage)
<fieldset>
<legend>@Model.Language.Name</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Descripcion)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Descripcion, new { Class = "wysiwyg" })
@Html.ValidationMessageFor(model => model.Descripcion)
</div>
</fieldset>
And the RoomType editor template:
@model DataAccess.RoomType
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.IdHotel)
<h3>
Información Básica
</h3>
<div class="editor-field">
@Html.EditorFor(model => model.RoomTypeInfos)
@Html.ValidationMessageFor(model => model.RoomTypeInfos)
</div>
I fixed it by querying the Languages table and setting it again to each RoomTypeInfo.Language, but if feels like a workaround.
What is the best practice in this case?