Hi guys, I'm really new at this and I was searching the web for an answer to my question and I couldn't find it, so here I am posting my question :)
I'm trying to create a new record in my table Facility. For my goreign keys I'm displaying the choices in tables instead of a dropdowns.
When the user clicks on the select link which is an Ajax.ActionLink(), I wanna retrieve the right record from the DB and set the foreign key of my object Facility to the one slected and replace the Div by a new Partial View.
The problem is when I try to submit the form, the Facility object doesnt seem to have the foreign key that I've just set in my ajax fuction in my controller.
And if the user has enter some data in the other fields of the create form, I don't them to lose what they already entered.
Here's my code.
Model only contains a Facility.
public ActionResult Create()
{
Model.Facility = new Facility();
return View(Model);
}
This is part of my Create View
<div id="FacilityTypePartialView">
<% Html.RenderPartial("FacilityType"); %>
</div>
This is my Partial View FacilityType
<% if (Model.IsNewFacility()) { %>
<p>
Id:
<%= Html.Encode(Model.Facility.FacilityType.FId)%>
</p>
<p>
Type:
<%= Html.Encode(Model.Facility.FacilityType.FType)%>
</p>
<p>
Description:
<%= Html.Encode(Model.Facility.FacilityType.FDescription) %>
</p>
<% } %>
<p>
<%= Html.ActionLink("Manage Facility Type", "Index","FacilityType") %>
</p>
<table id="FacilityTypesList">
<tr>
<th>
Select
</th>
<th>
FId
</th>
<th>
FType
</th>
<th>
FDescription
</th>
</tr>
<% foreach (var item in Model.GetFacilityTypes()) { %>
<tr>
<td>
<%=Ajax.ActionLink("Select",
"FacilityTypeSelect",
new { id = item.FId},
new AjaxOptions { UpdateTargetId = "FacilityTypePartialView" })%>
</td>
<td>
<%= Html.Encode(item.FId) %>
</td>
<td>
<%= Html.Encode(item.FType) %>
</td>
<td>
<%= Html.Encode(item.FDescription) %>
</td>
</tr>
<% } %>
</table>
Here's y Ajax Funcion
public PartialViewResult FacilityTypeSelect(int id) {
Facility facility = new Facility();
facility.FacilityType = _repository.GetFacilityType(id);
Model.Facility = facility;
if (this.Request.IsAjaxRequest() == false)
{
return PartialView("FacilityType/FacilityType", Model);
}
else
{
return PartialView("FacilityType/FacilityTypeSelected", Model);
}
}
Finally, my Post method
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create( Facility facility)
{
Model.Facility = facility;
if (ModelState.IsValid)
{
try
{
_repository.AddEntity(facility);
_repository.Save();
return RedirectToAction("Details", new { id = facility.Id });
}
catch { }
}
return View("Create", Model);
}
My Faciliy object coming from the View have the Facility.FacilityType set to nothing.