0

我声明了一个具有 4 个字符串字段的模型。其中 3 个在表单上是只读的:

public class HomeModel
    {
        [ReadOnly(true)]
        [DisplayName("Service Version")]
        public string ServiceVersion { get; set; }

        [ReadOnly(true)]
        [DisplayName("Session Id")]
        public string SessionId { get; set; }

        [ReadOnly(true)]
        [DisplayName("Visiting from")]
        public string Country { get; set; }

        [DisplayName("Search")]
        public string SearchString { get; set; }

    }

在填充模型后,我将模型传递给我的表单:

 [HttpGet]
        public ActionResult Index()
        {
            var model = new HomeModel
                            {
                                Country = "Australia",
                                SearchString = "Enter a search",
                                ServiceVersion = "0.1",
                                SessionId = "76237623763726"
                            };
           return View(model);  

        }

表格按我的预期显示:

<h2>Simple Lookup</h2>

@Html.LabelFor(m=>m.ServiceVersion): @Model.ServiceVersion<br/>
@Html.LabelFor(m=>m.SessionId): @Model.SessionId<br/>
@Html.LabelFor(m=>m.Country): @Model.Country<br/>
<p>
    @using(Html.BeginForm())
    {
        @Html.LabelFor(m => m.SearchString)
        @Html.TextBoxFor(m => m.SearchString)
        <button type="submit" name="btnSearch">Search</button>
    }
</p>

但是,当我提交表单并从表单中取回模型时,只填充了 SearchString 的值。

[HttpPost]
public ActionResult Index(HomeModel model)
{
    return View(model);
}

其他领域已经“丢失”是对的吗?MVC 不保留模型类的其他成员吗?如果这是预期的 - 有没有办法重新获得这些?还是我需要返回我的数据库,用旧值填充模型,然后使用表单模型中的新值?

It's possible the validity of wanting to read 'read-only' fields back from the model is questioned.. which is fair - but in the event that I find something suspect about the posted data, maybe I want to re-show the screen, and not have to re-read the data from a database again?

4

1 回答 1

0

This is the correct behavior. Only the elements inside form will be posted to your action. Since it is posting the form so your fields should be inside the form in order to get them on your post method.

Update

Also, you cannot read particular field on your action method if you have taken that field readonly on your view. eg: displaying using @Html.LabelFor. In order to get field back on your action use @Html.HiddenFor if field is not to be edited.

于 2013-03-30T07:22:17.723 回答