I have a table in which I need to insert Null value. Inside "FamilyTreeMember" table I have a column called "BirthMonth_Id" which is a FK to another table called BirthMonthDD. BirthMonthDD is my lookup table which I use it to generate DropDownList items.
In my current setup, I need to allow the end user to leave that field blank and save it as Null but it doesn't happen that way and instead it returns the old/same value. I don't get any error message. I can easily update the value from one thing to another. Example from February to August and ...
How can I fix this?
Model
public class FamilyTreeMember
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid FamilyTreeMemberId { get; set; }
public int? BirthDay { get; set; }
public virtual MonthDD BirthMonth { get; set; }
public int? BirthYear { get; set; }
public bool DOBEstimated { get; set; }
}
ViewModel
public class EditFamilyTreeMemberViewModel
{
[ScaffoldColumn(false)]
public string CaseId { get; set; }
[ScaffoldColumn(false)]
public string FamilyTreeMemberId { get; set; }
[UIHint("Day")]
[RegularExpression(@"([0-9]+)", ErrorMessage = "The {0} must be a number.")]
[Display(Name = "Day Of Birth")]
public int? BirthDay { get; set; }
[UIHint("ComboBox")]
[AdditionalMetadata("BindTo", "months")]
[Display(Name = "Month Of Birth")]
public int? BirthMonth { get; set; }
[UIHint("Year")]
[RegularExpression(@"([0-9]+)", ErrorMessage = "The {0} must be a number.")]
[Display(Name = "Year Of Birth")]
public int? BirthYear { get; set; }
[UIHint("Bool")]
[Display(Name = "DOB Estimated")]
public bool DOBEstimated { get; set; }
}
Controller (Update method)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(EditFamilyTreeMemberViewModel editfamilytreemember, Guid? ftm, Guid? cid, Guid? mid)
{
ViewBag.ftm = ftm;
ViewBag.cid = cid;
ViewBag.mid = mid;
if (ModelState.IsValid)
{
if (ftm == null)
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound);
}
using (db)
{
var ftmember = await db.FamilyTreeMember.SingleOrDefaultAsync(z => z.FamilyTreeMemberId == ftm);
ftmember.BirthDay = editfamilytreemember.BirthDay;
ftmember.BirthMonth = await db.MonthDD.SingleOrDefaultAsync(x => x.Id == editfamilytreemember.BirthMonth);
ftmember.BirthYear = editfamilytreemember.BirthYear;
ftmember.DOBEstimated = editfamilytreemember.DOBEstimated;
await db.SaveChangesAsync();
}
return RedirectToAction("Index", "FamilyTree", new { cid, mid });
}
return View();
}
ftmember.BirthMonth_Id = editfamilytreemember.BirthMonth;and you data model should have a propertypublic MonthDD int BirthMonth_Id { get; set; }null? That's the question you've got to ask yourself. You would want to try and reduce the amount ofnulls you are using.... Try looking at the null object pattern