asp.net-mvc 带有模型和 ViewDataDictionary 的 asp mvc 部分 - 如何访问 ViewDataDictionary?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4865162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
asp mvc partial with model and ViewDataDictionary - how do I access the ViewDataDictionary?
提问by house9
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?
这听起来可能很愚蠢,但我不知道如何从部分访问计数器 (i)?
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)
Create.cshtml(查看)
@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)
_TaskForm.cshtml(局部视图)
@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
注意上面的 String.Format 我是硬编码 0,我想使用 ViewDataDictionary 参数,该参数绑定到调用视图中的变量 i
回答by house9
Guess I posted too soon. This thread had the answer I was looking for
估计我发的太快了。这个线程有我正在寻找的答案
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} } )
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>