ASP.NET代码中的默认值未在视图中显示 [英] Default values with ASP.NET Code First not shown in View

查看:57
本文介绍了ASP.NET代码中的默认值未在视图中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先处理Entity Framework代码中的默认值的最佳方法是什么?我第一次使用ASP.NET MVC 4并且视图不显示所有输入字段,但是一些值如时间戳和输入记录的用户需要默认。



另外,对于编辑和更新,我如何允许用户在仅显示可编辑字段的视图中编辑数据,而不是在保存时将默认值设置为null。之前的日期似乎设置为null,因为它未显示在视图上。我想也许隐藏字段会有用,但是有更好的方法吗?

What is the best way to deal with default values in Entity Framework code first? I am using ASP.NET MVC 4 for the first time and the views dont show all the input fields, but some values like a timestamp and the user who entered the record need to be defaulted.

Also, for editing and updates how can I allow the user to edit data in a view that only shows editable fields and not set the default values to null when saved. The date from before seems to be set to null since it is not shown on the view. I thought maybe it would work to have hidden fields, but is there a better way?

推荐答案

让我们假设,你正在处理一个人实体在mvc。想想使用创建脚手架时的数据流:当你调用 NewPerson 动作(它的HttpGet版本)时,你可能只需要做一个简单的 return View(); 。好的,渲染了视图,你得到了html代码。是的,视图是引用模型的,但它只反映出来,你没有模型对象,只有模型类型。当然,可能有 DefaultValue [ ^ ]属性,但它适用于别的。帮助者可以使用它,但事实并非如此。

嗯,你还是不知道该怎么做......

好​​的,记住你是什么通常在NewPerson动作的HttpPost版本中进行。您可以使用实例填充模型,验证它,如果验证失败,则将模型对象传递到同一视图。哇,你渲染的HTML会有值。那么,为什么不在HttpGet版本中使用相同的概念呢?

所以:只需创建一个模型对象,用默认值填充它。当然,您可以将构造函数添加到模型类并在那里设置这些值。 (您可以添加默认值,如果您使用公共字段而不是公共属性,但我建议您不要)。并将填充了默认值的新创建的对象传递给视图。
Let''s assume, you are dealing with a "person" entity in mvc. Think about the data flow when you use a "create" scaffold: when you call the NewPerson action (the HttpGet edition of it), you will probably just make a simple return View();. Ok, the view is rendered, and you get the html code. Yes, the view is referencing the model, but it is only reflected, you don''t have a model object, just the model type. Of course, there could be a DefaultValue[^] attribute for that, but it''s for something else. It could be used by the helper, but it is not.
Well, you still don''t know what to do...
Ok, remember what you are usually doing in the HttpPost version of the NewPerson action. You get the model populated with an instance, you validate it, and if the validation fails, you pass the model object to the same view. And wow, you the rendered html will have the values. Well, why don''t use the same concept in the HttpGet version as well?
So: simply create a model object, fill it with the default values. Of course you can add a constructor to the model class and set these values there. (You could add default values, if you would use public fields instead of public properties, but I suggest you don''t). And pass this newly created object filled with the defaults to the view.


这篇关于ASP.NET代码中的默认值未在视图中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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