I am trying this in Create and Edit (my object is called 'entity'):-
if (ModelState.IsValid)
{
RemoveStringNull(entity);
db.Entity.Add(entity);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(entity);
}
Which calls this:-
private void RemoveStringNull(object entity)
{
Type type = entity.GetType();
FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
for (int j = 0; j < fieldInfos.Length; j++)
{
FieldInfo propertyInfo = fieldInfos[j];
if (propertyInfo.FieldType.Name == "String" )
{
object obj = propertyInfo.GetValue(entity);
if(obj==null)
propertyInfo.SetValue(entity, "");
}
}
}
It will be useful if you use Database First and your Model attributes get wiped out each time, or other solutions fail.