Alex Rivera | Logout

MVC3 - Model empty on post

Asked 2011-06-01T19:00:22.130
16

I have two models - category and article. I have pretty much the same delete views and controllers for both of them. The only difference is that it works for categories, but with articles I get empty model on HttpPost.

Categories:

    public ActionResult DeleteCat(int id)
    {
        Category cat = db.CategoryByID(id);
        if (cat != null)
        {
            return View(cat);
        }

        return RedirectToAction("Index");
    }

    [HttpPost]
    public ActionResult DeleteCat(Category model)
    {
        db.DeleteCategory(model.CategoryID);

        return RedirectToAction("Index");
    }

Articles:

    public ActionResult Delete(int id)
    {
        Article art = db.ArticleByID(id);
        if (art != null)
        {
            return View(art);
        }

        return RedirectToAction("Index");

    }

    [HttpPost]
    public ActionResult Delete(Article model)
    {
        db.DeleteArticle(model.ArticleID);

        return RedirectToAction("Index");
    }

Both views are generated by Visual Studio and I haven't changed them. When I want to delete a category, everything goes well. But when I want to delete an article, it first gets selected properly from database, then the view is displayed (everything is OK) but when I click the delete button the model is empty (all properties are either 0, null or false) and so the db.DeleteArticle throws an exception (there's no article with ArticleID = 0). Could anyone please provide me with any hints as to what should I check or how should I work around this?

Edit
Report

1 Answer

23

If the parameter for the model in the [HttpPost] Action is the same name as a property in the model it'll be null and will fail validation saying the field was invalid.

Example:

public class ContactMessage 
{
    public string Name { get; set; }
    public string sankdmfskm { get; set; }
}

[HttpPost]
public ActionResult Index(ContactMessage sankdmfskm)
{
...
}

sankdmfskm will be null.

Tested in MVC3 and MVC4.

answered 2012-01-30T11:02:10.843

Your Answer