views:

322

answers:

2

Hi,

I have:

"Task" Entity that holds a foreignkey to a "Project" Entity. In the MVC model I have a ProjectDetails view where i have a ActionLink for creating a new Task

I need to set the ProjectReference for the new Task object. The projectReference is passed by a url parameter (CreateTask?projectId=4)

In the projectDetails view I have:

<%= Html.ActionLink("Create New Task", "CreateTask", new {???Set the ProjectID???  })%>

1) How to set the ProjectReference "ProjectID"?

2) Is using ViewContext.Controller.ValueProvider["id"].RawValue for getting the urlparameter good?

Thank you!!

A: 

OK i found a solution but it's not that beautiful:

in projectdetails.aspx:

<%= Html.ActionLink("Create New Task", "CreateTask", new { projectId = ViewContext.Controller.ValueProvider["id"].RawValue })%>

in taskcreateMethod:

int projectId = Convert.ToInt32(Request.Params["projectId"]);
taskToCreate.Project= (from p in _db.Project where p.Id ==projectId select p).First();
_db.AddToTask(taskToCreate);
_db.SaveChanges();

return RedirectToAction("Details", "Home", new { id = projectId });
Michael Bavin
+1  A: 

Can't you just set the projectId in the model you're passing to the view? Something like:

public ActionResult ProjectDetails()
{
    ViewData["projectId"] = GetProjectId();

    return View();
}

Then in the view:

<%= Html.ActionLink("Create New Task", "CreateTask", ViewData["projectId"]) %>

Also, it's not a good practice to use Request.Params like that. Instead make an action with a "projectId" parameter like:

public ActionResult CreateTask(int projectId)

For more details see Passing Data in an ASP.NET MVC Application

Another thing is that one of the ideas of using ASP.NET MVC is to keep your urls readable. Try to use an url like /projects/5/createtask/ instead of /createtask.aspx?projectid=5. For more details on this, look at URL Routing with ASP.NET MVC by Scott Guthrie

Sander Rijken