首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MVC模型不能在表单中持久化

MVC模型不能在表单中持久化
EN

Stack Overflow用户
提问于 2013-03-30 15:18:08
回答 1查看 231关注 0票数 0

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

代码语言:javascript
复制
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; }

    }

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

代码语言:javascript
复制
 [HttpGet]
        public ActionResult Index()
        {
            var model = new HomeModel
                            {
                                Country = "Australia",
                                SearchString = "Enter a search",
                                ServiceVersion = "0.1",
                                SessionId = "76237623763726"
                            };
           return View(model);  

        }

表单的显示如我所料:

代码语言:javascript
复制
<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的值。

代码语言:javascript
复制
[HttpPost]
public ActionResult Index(HomeModel model)
{
    return View(model);
}

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

从模型中读回“只读”字段的有效性可能会受到质疑。这是公平的-但如果我发现发布的数据有可疑之处,也许我想重新显示屏幕,而不必再次从数据库中重新读取数据?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-30 15:22:18

这是正确的行为。只有表单中的元素才会发布到您的操作中。因为它是post表单,所以您的字段应该在表单内部,以便在post方法中获取它们。

更新

此外,如果在视图上将特定字段设为只读,则不能读取操作方法中的特定字段。例如:使用@Html.LabelFor显示。为了让字段返回到您的操作中,如果不编辑字段,则使用@Html.HiddenFor

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15716072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档