ASP MVC部分与模型和的ViewDataDictionary - 我怎么访问的ViewDataDictionary? [英] asp mvc partial with model and ViewDataDictionary - how do I access the ViewDataDictionary?

查看:258
本文介绍了ASP MVC部分与模型和的ViewDataDictionary - 我怎么访问的ViewDataDictionary?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建它与任务的集合更新两个相关的模型,在这个例子中的一个项目的形式,我想控制器接受已经从表单输入加载其任务集合的单个项目。我有这个工作,基本上是低于code,而不部分。

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?

示范

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(视图)

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(局部视图)

_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

请注意了上面的String.Format我硬编码0,我想用这势必变量i从调用视图

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

推荐答案

猜猜我太早公布。这个线程有我一直在寻找

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

<一个href=\"http://stackoverflow.com/questions/495351/asp-net-mvc-rc1-renderpartial-viewdatadictionary\">asp.net MVC RC1的RenderPartial的ViewDataDictionary

我结束了使用这种简洁的语法

I ended up using this terse syntax

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

然后在局部视图

@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>

这篇关于ASP MVC部分与模型和的ViewDataDictionary - 我怎么访问的ViewDataDictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆