0

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; }
}
3
  • Add the Event class to the question Commented Jun 3, 2020 at 20:14
  • public string ThemeColor { get; set; } Commented Jun 4, 2020 at 6:47
  • you can override getter and setter: private string _themeColor; public string ThemeColor{ get => string.IsNullOrEmpty(_themeColor) ? "Red" : _themeColor; set => _themeColor = value;} Commented Jun 5, 2020 at 6:52

1 Answer 1

1

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";
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you but your solutions not work for me when i add a new event make me color is NULL and not red color
You went with the second example, with checking yourself in the code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.