Search code examples
c#asp.net-mvcmodelstate

ModelState is invalid, object is fine?


I am currently working on a basic asp.net mvc app. Today I encountered a weird problem:

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Url, Homepage, Language, Country, Name")]FeedModel feedModel)
    {
        feedModel.Id = Guid.NewGuid().ToString();       
        feedModel.UserId = User.Identity.GetUserId();

        Debug.WriteLine(feedModel.UserId);

        if (ModelState.IsValid)
        {
            db.Feeds.Add(feedModel);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(feedModel);
    }

Apparently, ModelState.IsValid is always false, according to the debug-tools in VS due to the UserId value being null. However, using the Debug.WriteLine, the feedModel.UserId is displayed correctly.

The function is about receiving information from a view, adding the values for Id and UserId.

This is the feedModel-class:

public class FeedModel
{
    [Key]
    public string Id { get; set; }
    [Required]
    public string UserId { get; set; }
    [Required]
    public string Url { get; set; }
    [Required]
    public string Homepage { get; set; }
    [Required]
    public string Language { get; set; }
    [Required]
    public string Country { get; set; }
    [Required]
    public string Name { get; set; }
}

What am I doing wrong with there?

Thanks in advance!


Solution

  • You are only binding these values (Url, Homepage, Language, Country, Name) in the Post, but your model has Id and UserId as required. Model.IsValid is set at binding time which is before your controller action executes. Just because you set the Id and UserId in the method does not change the fact the model is invalid.