asp mvc partial with model and ViewDataDictionary - how do I access the ViewDataDictionary?

asp.net Mvc

asp.net Mvc Problem Overview


I am creating a form which updates two related models, for this example a Project with a collection of Tasks, I want the controller to accept a single Project which has its Task collection loaded from the form input. I have this working, essentially the below code without a partial.

This might sound silly but I cannot figure out how to access the counter (i) from the partial?

Model

public class Project
{
	public string Name { get; set; }
	public List<Task> Tasks { get; set; }
}

public class Task
{
	public string Name { get; set; }
	public DateTime DueDate { get; set; }
}

Create.cshtml (View)

@model MyWebApp.Models.Project

@using(Html.BeginForm("Create", "Project", FormMethod.Post, new { id = "project-form" }))
{
	<div>
		@Html.TextBox("Name", Model.Name)
	</div>
	
	@for(int i = 0; i < Model.Tasks.Count; i++)
	{
		@Html.Partial("_TaskForm", Model.Tasks[i], new ViewDataDictionary<int>(i))
	}
	
}

_TaskForm.cshtml (partial view)

@model MyWebApp.Models.Task

<div>
	@Html.TextBox(String.Format("Tasks[{0}].Name", 0), Model.Name)
</div
<div>
	@Html.TextBox(String.Format("Tasks[{0}].DueDate", 0), Model.DueDate)
</div

NOTE the String.Format above I am hardcoding 0, I want to use the ViewDataDictionary parameter which is bound to the variable i from the calling View

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

Guess I posted too soon. This thread had the answer I was looking for

https://stackoverflow.com/questions/495351/asp-net-mvc-rc1-renderpartial-viewdatadictionary

I ended up using this terse syntax

@Html.Partial("_TaskForm", Model.Tasks[i], new ViewDataDictionary { {"counter", i} } )

Then in partial view

@model MyWebApp.Models.Task
@{
    int index = Convert.ToInt32(ViewData["counter"]);
}

<div>
    @Html.TextBox(String.Format("Tasks[{0}].Name", index), Model.Name)
</div>
<div>
    @Html.TextBox(String.Format("Tasks[{0}].DueDate", index), Model.DueDate)
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhouse9View Question on Stackoverflow
Solution 1 - asp.net Mvchouse9View Answer on Stackoverflow