DisplayFor is not keeping data in ViewModel on Pos

2019-07-25 06:24发布

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条回答
放我归山
2楼-- · 2019-07-25 06:51

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.

查看更多
登录 后发表回答