[英]Can I get the index from Knockout Foreach Template and pass to Html.EditorFor?
Using MVC 4, I am looking for a simple way to combine a knockout template and an EditorFor. 使用MVC 4,我正在寻找一种结合淘汰模板和EditorFor的简单方法。 I almost have what I'm looking for: 我几乎有我正在寻找的东西:
<div data-bind="template: { name:'cover', foreach: StockItems }"></div>
<script type="text/html" id="cover">
@Html.EditorFor(m => m.StockItems[0].Name, "MyTemplate",
new { htmlAttributes = new
{ data_bind = "value: $data.Name")
In the editor template I can bind the value from the knockout template: 在编辑器模板中,我可以绑定淘汰模板中的值:
@model KnockOut.Models.StockItem
@Html.TextBoxFor(model => model.Name, ViewData["htmlAttributes"])
This works pretty well and is almost a nice simple solution that meets my need. 这很好用,几乎是一个很好的简单解决方案,满足我的需要。 I have some very simple JavaScript to control adding, removing and posting JSON back to the server. 我有一些非常简单的JavaScript来控制添加,删除和发布JSON回到服务器。
The bit I don't like is that I hard code 0 here: m.StockItems[0].Name, which leads to the name and id attributes being generated as: 我不喜欢的是我在这里硬代码0:m.StockItems [0] .Name,它导致生成的name和id属性为:
id="StockItems_0__Name" name="StockItems[0].Name"
for each item I have. 对于我拥有的每件商品。 I could do something like use attr
: for id, name and whatever else and use $index()
to rename the accordingly: 我可以做一些像使用attr
:for id,name和其他任何东西,并使用$index()
来相应地重命名:
@Html.EditorFor(m => m.StockItems[0].Name, "MyTemplate",
new { htmlAttributes =new { data_bind =
"value: $data.Name,
attr:id:='StockIten_'+$index()+'.Name'")
I think probably that I need a more sophisticated EditorFor and use a C# @foreach() instead of the Knockout foreach and template and what I'm about to ask is not possible. 我想可能我需要一个更复杂的EditorFor并使用C#@foreach()而不是Knockout foreach和模板,而我要问的是不可能的。
However, is there anyway I can somehow get the index from the Knockout template to the EditorFor? 但是,无论如何我可以以某种方式从Knockout模板获取索引到EditorFor?
Of course, I'm also very interested on seeing a better way to tackle the whole problem. 当然,我也非常有兴趣看到解决整个问题的更好方法。
Thanks 谢谢
Html.EditorFor运行服务器端和knockout运行客户端站点,所以不,你不能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.