本文介绍了Html.HiddenFor 值属性未设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我本来可以使用

@Html.HiddenFor(x=> ViewData["crn"])

但是,我明白了,

<input id="ViewData_crn_" name="ViewData[crn]" type="hidden" value="500"/>

为了以某种方式规避该问题(id=ViewData_crn_ and name=ViewData[crn]),我尝试执行以下操作,但未设置value"属性.

To somehow circumvent that issue(id=ViewData_crn_ and name=ViewData[crn]), I tried doing the following, but the "value" attribute isn't getting set.

@Html.HiddenFor(x => x.CRN, new { @value="1"})
@Html.HiddenFor(x => x.CRN, new { @Value="1"})

生成

<input id="CRN" name="CRN" type="hidden" value="" />
<input Value="500" id="CRN" name="CRN" type="hidden" value="" />

我做错了什么吗??谢谢

Am I doing anything wrong??Thanks

推荐答案

您是否尝试过使用视图模型而不是 ViewData?以 For 结尾并采用 lambda 表达式的强类型辅助函数不能用于弱类型结构,例如 ViewData.

Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For and take a lambda expression cannot work with weakly typed structures such as ViewData.

我个人不使用 ViewData/ViewBag.我定义了视图模型,并让我的控制器操作将这些视图模型传递给我的视图.

Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.

例如在你的情况下,我会定义一个视图模型:

For example in your case I would define a view model:

public class MyViewModel
{
    [HiddenInput(DisplayValue = false)]
    public string CRN { get; set; }
}

让我的控制器操作填充这个视图模型:

have my controller action populate this view model:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        CRN = "foo bar"
    };
    return View(model);
}

然后让我的强类型视图简单地使用 EditorFor 助手:

and then have my strongly typed view simply use an EditorFor helper:

@model MyViewModel
@Html.EditorFor(x => x.CRN)

这会产生我:

<input id="CRN" name="CRN" type="hidden" value="foo bar" />

在生成的 HTML 中.

in the resulting HTML.

这篇关于Html.HiddenFor 值属性未设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 01:02