asp.net-mvc 在 MVC Web 应用程序中设置默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25398856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set the default value in MVC web application
提问by Zapnologica
I am trying to set the default Value of a field in an ASP.net MVC web application.
我正在尝试在 ASP.net MVC Web 应用程序中设置字段的默认值。
I am using database first so I have added a partial class for meta data as follows:
我首先使用数据库,所以我为元数据添加了一个部分类,如下所示:
[MetadataType(typeof(RadioRoutingMetadata))]
public partial class RadioRouting
{
}
public partial class RadioRoutingMetadata
{
[DefaultValue("%")]
public string Slot { get; set; }
[Required(ErrorMessage = "This field is requied")]
[DefaultValue(0)]
public int BlockStart { get; set; }
[Required(ErrorMessage = "This field is requied")]
[DefaultValue(499)]
public int BlockEnd { get; set; }
[DefaultValue(-1)]
public int FallBackBaseIdentifier { get; set; }
}
No after reading I see that [DefaultValue(T)]doesn't initialise the field to that value when being created. But do the Html helper methods not look at this field?
阅读后我看到[DefaultValue(T)]没有在创建时将字段初始化为该值。但是 Html 辅助方法不看这个字段吗?
here is my view:
这是我的观点:
<p>
@Html.LabelFor(model => model.Slot, htmlAttributes: new { @class = "control-label col-md-2" })
<span class="field">
@Html.EditorFor(model => model.Slot, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Slot, "", new { @class = "text-danger" })
</span>
</p>
<p>
@Html.LabelFor(model => model.BlockStart, htmlAttributes: new { @class = "control-label col-md-2" })
<span class="field">
@Html.EditorFor(model => model.BlockStart, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.BlockStart, "", new { @class = "text-danger" })
</span>
</p>
<p>
@Html.LabelFor(model => model.BlockEnd, htmlAttributes: new { @class = "control-label col-md-2" })
<span class="field">
@Html.EditorFor(model => model.BlockEnd, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.BlockEnd, "", new { @class = "text-danger" })
</span>
</p>
So When I now provide a Create Form I want these default values to be there in the form.
所以当我现在提供一个创建表单时,我希望这些默认值出现在表单中。
Do I have to initialize the Model object in the controller, set the default values, and then pass it through to the create view as if it was an edit view?
我是否必须在控制器中初始化 Model 对象,设置默认值,然后将它传递给创建视图,就好像它是一个编辑视图一样?
If so how can I create a constructor that initializes all the default values in the partial class?
如果是这样,我如何创建一个构造函数来初始化分部类中的所有默认值?
回答by Kartikeya Khosla
The DefaultValue attributeisn't used to set default values on properties like you want. In fact, it isn't directly used by the runtime at all. It's intended instead for use by the Visual Studio designer.
该DefaultValue attribute像你想是不是用来设置默认值的属性。事实上,运行时根本不直接使用它。它旨在供 Visual Studio 设计人员使用。
More info here:
更多信息在这里:
http://support.microsoft.com/kb/311339
http://support.microsoft.com/kb/311339
OR
或者
.Net DefaultValueAttribute on Properties
You can easily set default value of fields in MVC as :
您可以轻松地将 MVC 中字段的默认值设置为:
@Html.EditorFor(model => model.BlockEnd, new { htmlAttributes = new { @class = "form-control", @Value = "499" } })
Now with above code first time when form will loaded initial value of BlockEndwill be 499
现在使用上面的代码第一次加载表单时的初始值BlockEnd将是499
回答by Jason Evans
I suggest that you create a viewmodel class, and use that to set the default value e.g.
我建议您创建一个视图模型类,并使用它来设置默认值,例如
public class ExampleViewModel
{
public string Slot { get; set; }
[Required(ErrorMessage = "This field is required")]
public int BlockStart { get; set; }
// Include other properties as required.
}
In your controller, make use of the viewmodel like this:
在您的控制器中,像这样使用视图模型:
public ActionResult Index()
{
var viewModel = new ExampleViewModel();
viewModel.Slot = "A default value";
return View(viewModel);
}
[HttpPost]
public ActionResult Index(ExampleViewModel viewModel)
{
// Do whatever you need to do with the values in viewModel e.g. save them to database.
}
Looking at your view code, it seems you wouldn't have to change that, other than putting this at the top
查看您的视图代码,除了将其放在顶部之外,您似乎不必更改它
@model ExampleViewModel
I recommend using viewmodels, rather than passing actual data classes, to views since that makes changing view code a lot easier. Also the added flexability you get from using viewmodels is a plus e.g. using a data class, say Car, makes it hard if you also want to display data from another data class, say Driver, on the same view. By using a viewmodel named "VehicleDetailsViewModel" you can have properties such as "DriverName", "CarMake", "CarModel", etc.
我建议使用视图模型,而不是将实际数据类传递给视图,因为这样可以更轻松地更改视图代码。此外,您从使用视图模型中获得的额外灵活性是一个加分项,例如使用数据类,例如 Car,如果您还想在同一视图上显示来自另一个数据类(例如 Driver)的数据,则会变得很困难。通过使用名为“VehicleDetailsViewModel”的视图模型,您可以拥有诸如“DriverName”、“CarMake”、“CarModel”等属性。
EDIT: Ahh, OK so you're using a viewmodel already. In that case, I suggest you set the default values in the constructor of the viewmodel class.
编辑:啊,好的,所以你已经在使用视图模型了。在这种情况下,我建议您在 viewmodel 类的构造函数中设置默认值。
public ExampleViewModel()
{
this.Slot = "Whatver";
// etc.
}
I think this is much better than my previous suggestion of setting a default value in the action method above. But you have the choice of selecting where you want to set a default value, it's not set in stone.
我认为这比我之前在上面的 action 方法中设置默认值的建议要好得多。但是您可以选择要设置默认值的位置,它不是一成不变的。
I'm not sure if the DefaultValueis actually being picked up by the Razor parser.
我不确定DefaultValueRazor 解析器是否真的获取了它。
回答by Soft-Brain
Kindly try this:
请试试这个:
public partial class RadioRoutingMetadata
{
public string Slot { get; set; } = "%";
[Required(ErrorMessage = "This field is requied")]
public int BlockStart { get; set; } = 0;
[Required(ErrorMessage = "This field is requied")]
public int BlockEnd { get; set; } = 499;
public int FallBackBaseIdentifier { get; set; } = -1;
}

