I am not sure why the ModelState validity checks keep returning false, hence preventing a write to DB action, even though values supplied to all the properties are of right DataType and successfully passed to the HttpPost method. Here is my code below:
**My Models**
/* public class Product
{
[Key]
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
} */
**My ViewModel**
/* public class ProductViewModel_02
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
[Required(ErrorMessage = "..")]
public int? CategoryID { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
*/
**My Controller**
/*
[HttpGet]
public IActionResult Create()
{
var model = new ProductViewModel_02()
{
CategoryList = GetCategoriesListItems()
};
return View(model);
}
[HttpPost]
public IActionResult Create(ProductViewModel_02 pvm)
{
if(ModelState.IsValid)
{
return RedirectToAction("Index");
}
pvm.CategoryList = GetCategoriesListItems();
return View(pvm);
}
private IEnumerable<SelectListItem> GetCategoriesListItems()
{
return db.Categories.Select(x => new SelectListItem
{
Value = x.CategoryID.ToString(),
Text = x.CategoryName
});
}
*/
**my View Page**
/*
@Html.DropDownListFor(x => x.CategoryID, new SelectList(Model.CategoryList, "Value", "Text"),
"Select", new{})#
*/
ModalState is always invalid when form is submitted, below is the result of my debugging. The List object is null and Invalid, amongst the rest of the properties.[enter image description here](https://i.stack.imgur.com/QcG48.jpg)
CodePudding user response:
why the ModelState validity checks keep returning false
I test your code , find you bind values to properties(eg CategoryID
) successfully, but you don't give the value to the CategoryList
from view to controller. The CategoryList's value is null, so the ModelState validity checks keep returning false.
Below is a way to solve the problem, hope it can help you, try to remove below line from your YourProjectName.csproj
file
<Nullable>enable</Nullable>
Read this to know more.