简体   繁体   English

MVC @Html.HiddenFor 呈现没有值的 html 表单

[英]MVC @Html.HiddenFor renders html form with no value

Caution, before You read the rest注意,在您阅读其余部分之前

This question is not about POST method, redisplaying view with submited form or binding input values to controller method parameters.这个问题与 POST方法、重新显示带有提交表单的视图或将输入值绑定到控制器方法参数无关 It's purely about rendering the View using html helper ( HiddenFor or Hidden - both returns the same).这纯粹是关于使用 html 帮助程序( HiddenForHidden - 两者返回相同)呈现视图


I created a simple hidden field using HiddenFor helper我使用HiddenFor助手创建了一个简单的隐藏字段

@Html.HiddenFor(m => m.ProductCode)

and my problem is that value for this hidden field is rendered as null:我的问题是这个隐藏字段的值呈现为空:

<input id="productCode" name="productCode" type="hidden" value/>

Even if I set it when instantiating a model and of course it's confirmed with debugging ( it always has a value ).即使我在实例化模型时设置了它,当然它也通过调试得到确认(它总是有一个值)。
So instead it should look like this:所以它应该是这样的:

<input id="productCode" name="productCode" type="hidden" value="8888888"/>

Because I know there are some questions like this one (actually all of them refer to changing form values during form POST) I included list of things I tried already.因为我知道有一些像这样的问题(实际上所有这些问题都是指在表单 POST 期间更改表单值)我列出了我已经尝试过的事情。 My code is right below this section which I belive to be essential.我的代码就在这部分的正下方,我认为这是必不可少的。


So far I tried:到目前为止,我尝试过:

  • ModelState.Clear() everywhere possible - cause as we know the value from ModelState is first place where it looks for the value . ModelState.Clear() 无处不在 -因为我们知道来自 ModelState 的值是它寻找值的第一个地方 NO EFFECT which I expected, cause my ModelState is empty (my case is not about changing value during POST in controller as in many questions like that), so it should take value from my view model.没有我预期的效果,因为我的 ModelState 是空的(我的情况不是在控制器的 POST 期间更改值,就像许多类似的问题一样),所以它应该从我的视图模型中获取值。
  • Not using HiddenFor helper, but pure html instead.不使用HiddenFor助手,而是使用纯 html。 WORKS , but its just workaround , not an answer to the problem. WORKS ,但它只是解决方法,而不是问题的答案。
  • Duplicating line with helper in view as follows:在视图中复制带有助手的行,如下所示:
@Html.HiddenFor(m => m.ProductCode)
@Html.HiddenFor(m => m.ProductCode)

PARTIALLY WORKS Produces first input as value/> and second as value="8888888"/> which indicates that there is probably something that hides initial property value. PARTIALLY WORKS 将第一个输入作为value/>和第二个作为value="8888888"/> ,这表明可能存在隐藏初始属性值的东西。 Anyway, I found nothing in ViewData at any point, nor in query string .无论如何,我在任何时候都没有在 ViewData 中找到任何内容,也没有在 query string 中找到 Obviously I can't accept it this way, no explonation needed I guess.显然我不能接受这种方式,我猜不需要解释。

  • Changing name of the property.更改属性名称。 Originally it was ProductCode .最初它是ProductCode I changed it to productCode, ProdCode, ProductCodeasd, etc. and all of these WORKS .我将其更改为productCode、ProdCode、ProductCodeasd 等,以及所有这些WORKS Again, it looks like there is something that hides/updates the value, but again - 100% sure there is no JS or anything else doing it.同样,看起来有些东西可以隐藏/更新该值,但同样 - 100% 确定没有 JS 或其他任何东西在做这件事。 So still no answer found - just workaround again.所以仍然没有找到答案 - 再次解决方法
  • Explicitly setting the value for HiddenFor: @Html.HiddenFor(x => x.ProductCode, new {Value = @Model.ProductCode}).显式设置 HiddenFor 的值:@Html.HiddenFor(x => x.ProductCode, new {Value = @Model.ProductCode})。 NO EFFECT , renders the same way. NO EFFECT ,以同样的方式呈现。
  • Using @Html.Hidden instead of @Html.HiddenFor .使用@Html.Hidden而不是@Html.HiddenFor NO EFFECT , with name set as ProductCode it renders the same way. NO EFFECT ,名称设置为ProductCode它呈现相同的方式。

One more thing I found interesting.我发现有趣的另一件事。 Reading html with Display page source in Chrome [ctrl+U] shows that value is valid value="8888888"/> , but in DevTools it's still value/> and of course submitting the form passes null to Controller method.在 Chrome [ctrl+U]中使用Display page source读取 html显示value 是有效value="8888888"/> ,但在 DevTools 中它仍然是value/>并且当然提交表单将 null 传递给 Controller 方法。


Model模型

public class Product
    {
        public string Description { get; set; }
        public int Quantity { get; set; }
        public string ProductCode { get; set; }
        public string ImageUrl { get; set; }

        public Product(string desc, string productCode, string imgUrl)
        {
            Description = desc;
            ProductCode = productCode;
            ImageUrl = imgUrl;
        }
    }

View看法

@model Product

@using (Html.BeginForm("UpdateCart", "Cart"))
{
    <div class="row pad10">

        <div class="col-sm-6 text-center">
            <img src="@Model.ImageUrl" width="300" height="300" />
        </div>
        <div class="col-sm-6 text-justify">
            <p>@Model.Description</p>
            <div class="row padding-top-2">
                <div class="col-sm-6">
                    <label>@CommonResources.Quantity: </label>
                </div>
                <div class="col-sm-4">
                    @Html.TextBoxFor(m => m.Quantity, new
                    {
                        @class = "form-control",
                        @data_val_required = CommonResources.FieldRequired,
                        @data_val_number = CommonResources.ValidationNumber
                    })
                    @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })
                    @Html.HiddenFor(m => m.ProductCode)
                </div>
            </div>
        </div>
    </div>
    <div class="text-center col-xs-12 padTop20 padBottom20">
        <input type="submit" value="Submit" class="whtBtn pad" />
    </div>
}

Controller控制器

The view is returned from controller with RedirectToAction as follows:视图是从控制器返回的 RedirectToAction 如下:
ValidateAndProceed -> ResolveNextStep (here redirection occurs) -> ShowProduct ValidateAndProceed -> ResolveNextStep(这里发生重定向)-> ShowProduct

        public ActionResult ValidateAndProceed()
        {
            var order = Session.Current.Order;
            var lang = LangService.GetSelectedLanguage();
            var invoice = Session.Current.CurrentInvoice;
            var localCurrency = Session.Current.LocalCurrencyInfo;

            List<CheckoutValidationFieldError> errors = new List<CheckoutValidationFieldError>();

            errors = ValidationService.ValidateAddress(order);
            if (errors.Count > 0)
            {
                return RedirectToAction("InvalidAddress", "Address", new { serializedErrors = JsonConvert.SerializeObject(errors) });
            }

            return ResolveNextStep(order, invoice);
        }

        public ActionResult ResolveNextStep(IOrder order, IInvoice invoice)
        {
            if (OrderService.ShowProductView(order, invoice))
            {
                return RedirectToAction("ShowProduct");
            }
            return RedirectToAction("Summary");
        }

        public ActionResult ShowProduct()
        {
            Product model = ProductService.GetProduct(Session.Current.CurrentInvoice);
            return View("~/Views/Product.cshtml", model );
        }

Finally, what can cause such a weird behavior?最后,是什么导致了这种奇怪的行为? I've already ran out of options.我已经没有选择了。 Maybe anyone had problem like mine before, would appreciate any clue on this case.也许任何人以前都遇到过像我这样的问题,希望对此案有任何线索。

I debugged the whole process of rendering the view (got into .Net sources) checking every possible place that could make it fail and found nothing.我调试了渲染视图的整个过程(进入 .Net 源)检查每个可能导致它失败的地方,但什么也没找到。

After @AndyMudrak and @Jeremy Lakeman comments I decided to try again to find JavaScript responsible for that behavior, but deeper than I did before.在@AndyMudrak 和@Jeremy Lakeman 发表评论后,我决定再次尝试找到对这种行为负责的 JavaScript,但比以前更深入。 What I found was a really silly script where element Id is being concatenated from three strings what I didn't expect, cause it's really badly implemented.我发现的是一个非常愚蠢的脚本,其中元素 Id 是从我没想到的三个字符串中连接起来的,因为它的实现非常糟糕。 So finally - JavaScript is doing it and there is no bad behavior from framework etc.所以最后 - JavaScript 正在这样做,并且框架等没有不良行为。

Actually I am a bit disappointed (even if it's good to know this easy answer) cause it looked much more complicated than it really was and it took me hours to find out how simple it is :|实际上我有点失望(即使知道这个简单的答案很好)因为它看起来比实际复杂得多,而且我花了几个小时才发现它有多简单:|

Thanks for comments, sorry for final simplicity.感谢您的评论,抱歉最后的简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM