71

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

1 Answer 1

142

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

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.