I have two classes where one is a parent class for the other. The basic CRUD functions was created in the controller. In the design of my table I have the parent id in my child class as the foreign key. In the view for Create function of the child, I am asked to enter the parent ID. I have changed the Create to accept the ID of the parent. But when I remove the code for selecting the parent id in the view I get exception in my Create. Is there a way I can set the parent ID in both my create functions(Over loaded functions).
public ActionResult Create(int? id)
{
ViewBag.LsystemID = new SelectList(db.Lsystem, "LsystemID", "LsystemName",id);
ViewBag.TCID = new SelectList(db.TC, "TCID", "TCName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OptionID,OptionName,TCID,LsystemID")] Option option)
{
if (ModelState.IsValid)
{
db.Option.Add(option);
db.SaveChanges();
return RedirectToAction("Index");
}
// ViewBag.LsystemID = new SelectList(db.Lsystem, "LsystemID", "LsystemName", op);
ViewBag.TCID = new SelectList(db.TC, "TCID", "TCName", option.TCID);
return View(option);
}
View
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.OptionName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.OptionName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.OptionName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.TCID, "TCID", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownList("TCID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.TCID, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.LsystemID, "LsystemID", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownList("LsystemID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.LsystemID, "", new { @class = "text-danger" })
<input type="submit" value="Create" class="btn btn-default" />
}
How can I pass the value LsystemID without being shown in the View?
EDIT 1 : Adding Model class
public class Lsystem
{
public int LsystemID { get; set; }
public string LsystemName { get; set; }
public virtual ICollection<Option> Options { get; set; }
// public int OptionId { get; set; }
}
public class Option
{
public int OptionID { get; set; }
public string OptionName { get; set; }
public int TCID { get; set; }
public virtual TC tc { get; set; }
public virtual Lsystem Lsystem { get; set; }
public int LsystemID { get; set; }
public virtual ICollection<OptionValue> OptionValues { get; set; }
}