为什么我在Html.HiddenFor中收到变量范围错误(CS0136)? [英] Why do I get a variable scope error (CS0136) in a Html.HiddenFor?

查看:109
本文介绍了为什么我在Html.HiddenFor中收到变量范围错误(CS0136)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是MVC3/Razor视图文件中的简化代码段:

Here is a stripped-down code snippet from a MVC3/Razor view file:

@foreach (var item in Model.Stuff.Items){
<tr>
  <td>@item.Title</td>
</tr>
<tr>
  <td>
    @using (Html.BeginForm()) {
        @item.Title
        @Html.HiddenFor(item => item.Title)
    }
  </td>
</tr>
}  @* End of Items foreach loop *@

标题显示在第一行. 它还显示在表单内部.但是尝试在HiddenFor中使用它时出现错误

The title shows on the first row. It also shows inside the form. But trying to use it in the HiddenFor I get error CS0136: A local variable named 'item' cannot be declared in this scope because it would give a different meaning to 'item', which is already used in a 'parent or current/child' scope to denote something else

我不知道为什么会这样;在item => item.Title中,第一个项目"实际上只是匿名函数中的参数名称,不是吗?

I don't get why that would be the case; in item => item.Title the first "item" is effectively just a parameter name in an anonymous function, isn't it?

当我将其更改为:@Html.HiddenFor(s => s.Title)出现错误CS1963时,表达式树可能不包含动态操作.

When I change it to: @Html.HiddenFor(s => s.Title) I get error CS1963, An expression tree may not contain a dynamic operation.

背景:目的是在Model.Stuff.Items中每个条目有两个表行,第一个以静态HTML形式提供当前信息,第二个以其编辑形式提供. (使用javascript可以随时隐藏一个或另一个.)该表单将提交到此控制器上的另一个操作.所有表格都提交到相同的URL;隐藏的值将标识要更新的行.

Background: the intention is to have two table rows per entry in Model.Stuff.Items, the first giving current information as static HTML, the second an edit form for it. (One or the other will be hidden at any time using javascript.) The form will submit to another action on this controller. All the forms submit to the same URL; the hidden values will identify which row is being updated.

推荐答案

使用@Html.HiddenFor(x => item.Title)

@foreach (var item in Model.Stuff.Items){
<tr>
  <td>@item.Title</td>
</tr>
<tr>
  <td>
    @using (Html.BeginForm()) {
        @item.Title
        @Html.HiddenFor(x => item.Title)
    }
  </td>
</tr>
}

这篇关于为什么我在Html.HiddenFor中收到变量范围错误(CS0136)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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