剃刀MVC模式是在Save操作丢失数据 [英] Razor MVC model is losing data on Save action

查看:102
本文介绍了剃刀MVC模式是在Save操作丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用TextBoxFor其中包含的数据1文本框。

I have 1 textbox using TextBoxFor which contains the data.

我有一个ID为模型和其他一些基本的数据,但由于标签直接显示到视图中。

I have an Id for the Model and some other basic data but displayed as labels directly into the View.

当我只提交文本字段的模型数据的形式,其他的一切都是空包括标识。这意味着它不会保存到数据库中。

When I submit the form only the textbox field has data on the model, everything else is null including the Id. This means it won't save into the database.

什么会导致所有字段为空除了文本?

What would cause all the fields to be null apart from the textbox?

推荐答案

这是网络的工作方式,只有形成元素与表单提交和标签不构成元素。

This is the way the web works, only form elements are submitted with the form and labels are not form elements.

通常什么发生在这里的是你:

What commonly happens here is that you:


  1. 渲染一个隐藏字段( Html.Hidden / Html.HiddenFor )包含该ID的文本框沿

  2. 接受你的控制器动作(或参数的对象)的修改

  3. 水合物从你的资料库/数据库中标识psented对象重新$ P $实例

  4. 将更改应用到水合实例

  5. 验证对象的状态,并更新你的资料库/数据库(或任何你打​​算用它做)

  1. Render a hidden field (Html.Hidden / Html.HiddenFor) containing the Id along with the text boxes
  2. Accept the changes in your controller action (as parameters or an object)
  3. Hydrate the instance of the object represented by Id from your repository/database
  4. Apply the changes to the hydrated instance
  5. Validate the state of the object and update your repository/database (or whatever you were planning on doing with it)

由于发布的数据类往往是由于其缺少的属性无效(标记为 [必需] )后,其非常普遍,使一个新的类仅具有被改变的特性(称为命令模式)。这个类可以有自己的验证属性,因此不会与表单验证渣土。

As the posted data class is often "invalid" due to its missing properties (those marked as [Required] for example), its very common to make a new class that has only the properties being changed (called a "command model"). This class can have its own validation properties and thus not muck with your form validation.

这篇关于剃刀MVC模式是在Save操作丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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