Question

I have a model item

public class EntryInputModel
{
    ...

    [Required(ErrorMessage = "Description is required.", AllowEmptyStrings = false)]
    public virtual string Description { get; set; }
}

and a controller action

public ActionResult Add([Bind(Exclude = "Id")] EntryInputModel newEntry)
{
    if (ModelState.IsValid)
    {
        var entry = Mapper.Map<EntryInputModel, Entry>(newEntry);

        repository.Add(entry);
        unitOfWork.SaveChanges();
        return RedirectToAction("Details", new { id = entry.Id });
    }
    return RedirectToAction("Create");
}

When I create an EntryInputModel in a unit test, set the Description property to null and pass it to the action method, I still get ModelState.IsValid == true, even though I have debugged and verified that newEntry.Description == null.

Why doesn't this work?

Was it helpful?

Solution

This is because model binding doesn't take place when you invoke an action from a test. Model binding is the process of mapping posted form values to a type and pass it as a parameter to an action method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top