DisplayFor不是在视图模型上保存数据的回发 [英] DisplayFor is not keeping data in ViewModel on PostBack

查看:205
本文介绍了DisplayFor不是在视图模型上保存数据的回发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经被其他问过,但还是不明白这一点。
我使用MVC3剃须刀,我有屏幕输入的麻烦门票。
一旦数据(一个textarea注)输入后,控制器重定向回​​同一屏幕。
大部分数据仅用于显示。如果我使用DisplayFor或DisplayTextFor,数据
没有被调回。我已经使用HiddenFor。这样可行。不过,我一直在听证会
从别人那HiddenFor不理想。我不想因为editorfor,我想轻松地禁用该字段。 (按照工作说HiddenFor是错的,但不会说为什么:<笑)

剃须刀

  @ Html.DisplayTextFor(M = GT; m.Ticket.Name)

视图模型

 公共类TicketDetailsViewModel
    {
        [DisplayName的(客户名称)]
        公共字符串名称{;组; }控制
        [HttpPost]
        公众的ActionResult详细信息(TicketDetailsViewModel视图模型)
        返回RedirectToAction(详细信息);


解决方案

仅是输入或其他形式的控制的一部分值将发布返回给客户端。 DisplayFor只是意味着该模型显示它的数据,没有别的。

您有两个选项;使用隐藏字段,以便在模型每次填入数据,或者再次读取该值。前一种方法就可以了,如果你的数据不敏感,因为最终用户可以改变隐藏的价值和重新发布表单。因此,例如单价将不被东西,你会想永远从客户端得到,因为即使在一个隐藏字段恶意用户可以修改单价。在这种情况下,你总是想要自己重新加载数据和重新填充模型。

有什么不妥,要么;如果数据是不可编辑的,你需要显示它,你需要在每次得到它。我个人宁可谨慎,每一次重新读取该服务器上的只读数据,而不是把数据放到隐藏字段。

This question has been asked before by other, but still don't get it. I am using MVC3 Razor and I have screen for entering trouble tickets. Once data (a textarea note) is entered, the controller redirects back to the same screen. Most of the data is for display only. If I use DisplayFor or DisplayTextFor, the data is not being posted back. I have used HiddenFor. That works. However, I keep hearing from others that HiddenFor is not ideal. I don't want to editorfor because, I want to easily disable the field. (I follow working says HiddenFor is wrong, but won't say why. :< lol)

Razor

@Html.DisplayTextFor(m => m.Ticket.Name)

ViewModel

    public class TicketDetailsViewModel
    {
        [DisplayName("Customer Name")]
        public string Name { get; set; }

Control
        [HttpPost]
        public ActionResult Detail(TicketDetailsViewModel viewModel)
        return RedirectToAction("Detail");

解决方案

Only values that are part of an input or other form control will be posted back to the client. DisplayFor is just meant for the model to display its data, nothing else.

You have two options; use a hidden field so that the model is populated with the data each time, or fetch the value again. The former method would be fine if your data isn't sensitive because an end user can change the hidden value and repost your form. So for example a UnitPrice would NOT be something you'd want to ever get from the client as even in a hidden field a malicious user can modify the unit price. In that case you'd always want to reload the data yourself and repopulate the model.

There's nothing wrong with that either; if the data isn't editable and you need to display it, you need to get it every time. I'd personally err on the side of caution and refetch the read-only data each time on the server and not put the data into hidden fields.

这篇关于DisplayFor不是在视图模型上保存数据的回发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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