public ActionResult Update(string id)
{
Device record = new Device(); // OK
record = record.Find(new Guid(id), service); // OK
if (record.secondValue.HasValue) // <---
record.secondSelectList.FirstOrDefault(i => i.Value == record.secondValue.ToString()).Selected = true;
return View(record);
}
The above code finds a device for a given ID, then sets the DropDownList If secondValue has a value, if not then skip.
The code works perfectly, but in many actions in many controllers I have to to put an IF condition to check if xxxValue is indeed have a value.
I can’t do this directly:
record.secondSelectList.FirstOrDefault(i => i.Value == record.secondValue.ToString()).Selected = true;
because at any time FirstOrDefault may return a null reference, which will instantly will throw an exception because of using the .Selected property.
OK, my question is how to set the DropDownList with no need of using If conditions?
I imagine instead of using FirstOrDefault(), I will use SetSelected().
record.secondSelectList.SetSelected(i => i.Value == record.secondValue.ToString());
Where is SetSelected() method I will handle the null result.
How can I do this?
You can do it inline:
Or, probably more clearly: