DisplayFor is not keeping data in ViewModel on PostBack

两盒软妹~` 提交于 2019-12-24 09:21:47

问题


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");

回答1:


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.



来源:https://stackoverflow.com/questions/18448247/displayfor-is-not-keeping-data-in-viewmodel-on-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!