Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC set foreign key without dropdown

I'm having issues when creating a new db object using EF. It has a foreign key which, when using the preset views, is set using a dropdown menu.

@Html.DropDownList("ParentID", null, htmlAttributes: new { @class = "form-control" })

The issue is that I don't want to edit this value, it needs to be set in the controller but I cannot access the value.

public ActionResult Create()
{
    //I don't want a select list ParentID needs to be passed from the parent.
    ViewBag.ParentID = new SelectList(db.Parents, "ParentID", "ParentName"); 
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ChildID,ParentID,ChildName")] Child child)
{
    if (ModelState.IsValid)
    {
        //How do I set child.ParentID without a select list???
        db.Child.Add(child);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.ParentID = new SelectList(db.Parents, "ParentID", "ParentName", child.ParentID); //I don't need this
    return View(child);
}

What's the usual way this is achieved?

like image 374
Dom Avatar asked May 22 '26 21:05

Dom


1 Answers

You probably wanna pass ParentID from another Action Method but i wonder why you wanted to do that by means of SelectList (if there is no selection out there) though.

public ActionResult Create(int ParentID)
{
    //I don't want a select list ParentID needs to be passed from the parent.
    ViewBag.ParentID = ParentID; 
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ChildID,ParentID,ChildName")] Child child)
{
    if (ModelState.IsValid)
    {
        //How do I set child.ParentID without a select list???
        db.Child.Add(child);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return RedirectToAction("List");
}

And in the View :

 @Html.Hidden("ParentID", (object) ViewBag.ParentID)

i think it should be the way to go.

like image 106
Behnam Esmaili Avatar answered May 25 '26 11:05

Behnam Esmaili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!