MVC3 Populate 'Create' View for related object

649 Views Asked by At

Related post: Populating a select box in a form using related ID in MVC3

I've got a Listview generated using MVC3 and ADO.NET Linq-to-Entities.

I have been able to create a simple list view, with an "Create" & "Edit" Action Link Command for creating a 'related object'.

 @Html.ActionLink("Create Shipping Profile", "../PrintProfile/Create", new { id = item.ProductId }) |
 @Html.ActionLink("Edit Shipping Profile", "../PrintProfile/Edit", new { id = item.ProductId })

When I create the 'PrintProfile' I want the 'Create' view to be 'pre-populated' with the "ProductId" (which is the database table relation), so that I can create the profile, and edit the associated profile for each item in the list.

Here is the Create Controller for the PrintProfile:

    public ActionResult Create(int ProductId)
    {
        var entities = new CS_ShippingProfiles();
        entities.ProductId = ProductId; // Assign the ProductId I want to 'create'
        return View(entities);
    }

    [HttpPost]
    public ActionResult Create(CS_ShippingProfiles Profile)
    {
        if (ModelState.IsValid)
        {
            var entities = new LabelServiceEntities();
            entities.AddToCS_ShippingProfiles(Profile);
            entities.SaveChanges();

            return Redirect("/Products");
        }
        return View(Profile);
    }

But When I follow the link, I get a 'Null' parameter exception! What am I doing wrong?!

1

There are 1 best solutions below

1
On BEST ANSWER

Your action parameter on the Create action is called ProductId so make sure you generate correct links:

@Html.ActionLink(
    "Create Shipping Profile", 
    "Create", 
    "PrintProfile", 
    new { ProductId = item.ProductId }, 
    null
) 
|
@Html.ActionLink(
    "Edit Shipping Profile", 
    "Edit", 
    "PrintProfile", 
    new { ProductId = item.ProductId }, 
    null
)

Also notice how controller and actions are specified instead of using some relative urls as you do (../PrintProfile/Create).