Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何在ASP.NET MVC中生成默认值_Asp.net Mvc - Fatal编程技术网

Asp.net mvc 如何在ASP.NET MVC中生成默认值

Asp.net mvc 如何在ASP.NET MVC中生成默认值,asp.net-mvc,Asp.net Mvc,我想在添加新事件时创建默认颜色 现在颜色设置为空 [HttpPost] public JsonResult SaveEvent(Event e) { var status = false; if (e.EventID > 0) { //Update the event var v = db.Events.Where(a => a.EventID == e.EventID).FirstOr

我想在添加新事件时创建默认颜色

现在颜色设置为空

[HttpPost]
public JsonResult SaveEvent(Event e)
{
        var status = false;

        if (e.EventID > 0)
        {
            //Update the event
            var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
            if (v != null) 
            {
                v.EventTitle = e.EventTitle;

                v.EventDescription = e.EventDescription;
                v.ThemeColor = e.ThemeColor;
            }
        }
        else
        {
            db.Events.Add(e);
        }

        db.SaveChanges();
        status = true;

        return new JsonResult { Data = new { status = status } };
    }
如何在添加事件时将颜色设置为红色

                public partial class Event
{
    public int EventID { get; set; }
    public string EventTitle { get; set; }
    public string EventDescription { get; set; }
    public Nullable<System.DateTime> StartDate { get; set; }
    public Nullable<System.DateTime> EndDate { get; set; }
    public string ThemeColor { get; set; }
}
公共部分类事件
{
public int EventID{get;set;}
公共字符串EventTitle{get;set;}
公共字符串EventDescription{get;set;}
公共可为空的起始日期{get;set;}
公共可为空的结束日期{get;set;}

公共字符串ThemeColor{get;set;} }
如果使用c#6或更高版本,可以使用此语法将默认值设置为属性

public string ThemeColor { get; set; } = "Red";
否则,您可以通过构造函数初始化

但是,如果您在有效负载中显式地将ThemeColor作为null发送,那么在调用该方法时,您需要手动检查ThemeColor是否为null,并在控制器中进行设置

例如:

v.ThemeColor = e.ThemeColor ?? "Red";
编辑:

您可以在方法的顶部添加空检查,并使用它涵盖这两种情况

if(e.ThemeColor == null)
{
    e.ThemeColor = "Red";
}

将事件类添加到questionpublic字符串ThemeColor{get;set;}中,您可以覆盖getter和setter:private string\u ThemeColor;公共字符串ThemeColor{get=>string.IsNullOrEmpty(_ThemeColor)?“Red”:_ThemeColor;set=>_ThemeColor=value;}谢谢你,但是当我添加一个新事件时,你的解决方案对我不起作用使我的颜色为NULL而不是红色你使用了第二个示例,在代码中检查了你自己?