Michael Heribert
Michael Heribert

Reputation: 69

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!

Upvotes: 0

Views: 449

Answers (2)

Fran
Fran

Reputation: 6520

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.

Upvotes: 5

Aamir Masood
Aamir Masood

Reputation: 321

ModelState gets set when the process of model binding is taking place. In your case the statement feedModel.UserId = User.Identity.GetUserId(); will not change the ModelState. Hence, the problem. You could check the validity of model through some different mechanism like using validators. If you don't want to use a different mechanism, you could set the default value of UserId property public string UserId { get; set; } = User.Identity.GetUserId(); or you could simply remove the Required attribute from the property so that it won't be reflected in the ModelState.

Upvotes: 3

Related Questions