I’m developing a simple project tracking website. A “Project” has “Tasks”, and a “Task” has “Subtasks”.
With the default scaffolding, when creating a “Task”, I have to manually select the “ProjectId” field of the “Task”.
I want to have it set up, that I will only be able to create a “Task” from within the “Project Detail” view.
I’m wondering how I can make it so I don’t have to manually select the “ProjectId” when creating a new task.
Here are snippets:
This is part of the Create.cshtml for the Task as auto generated by Visual Studio:
<div class="editor-label">
@Html.LabelFor(model => model.ProjectId, "Project Id")
</div>
<div class="editor-field">
@Html.DropDownList("ProjectId", String.Empty)
@Html.ValidationMessageFor(model => model.ProjectId)
</div>
This results in a drop down box where I have to manually select a project id.
This is the default “Create” action from the “Task” controller:
public ActionResult Create()
{
ViewBag.ProjectId = new SelectList(db.Projects, "Id", "Id");
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name");
ViewBag.TaskTypeId = new SelectList(db.TaskTypes, "Id", "Name");
return View();
}
What I would like is something like this:
public ActionResult Create()
{
ViewBag.ProjectId = RouteData.Values["Id"];
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name");
ViewBag.TaskTypeId = new SelectList(db.TaskTypes, "Id", "Name");
return View();
}
Somewhere I would have to set myTask.ProjectId = ViewBag.ProjectId. But I don’t know where.
Is this even the right way of doing it? Or is there a better way?
Thanks
Are you sure that you need the
DropDownListand not just a hidden input with a fixed value?It sounds like you want the value to be set and no visual representation of it should even be visible. If this is the case, you just pass your ID in the model and then bind it to a hidden input.