Aymen Ben Hassine
Aymen Ben Hassine

Reputation: 1

How make default value in ASP.NET MVC

I want to create a default color when I add a new event.

Now the color is set to NULL.

[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 } };
    }

How make ThemeColor red when I add the event ?

                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; }
}

Upvotes: 0

Views: 63

Answers (1)

Borka
Borka

Reputation: 803

If you use c# 6 or higher, you can use this syntax to set the default value to a property

public string ThemeColor { get; set; } = "Red";

Otherwise you can initialize via constructor.

But if you are explicitly sending the ThemeColor as null in the payload, when invoking the method then you'll need to manually check if ThemeColor is null and set it in the controller

For example:

v.ThemeColor = e.ThemeColor ?? "Red";

EDIT:

You can add the null check on top of the method and with that you'll cover both cases

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

Upvotes: 1

Related Questions