asp.net.netasp.net-coremodel-binding

I receive null after Model Binding


I receive variable with null values after model binding. What might be wrong here? Title is null, content is null after form submitting.

Create.cshtml

<form asp-action="Create" method="post">
            @Html.AntiForgeryToken()
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Content" class="control-label"></label>
                <textarea asp-for="Content" class="form-control"></textarea>
                <span asp-validation-for="Content" class="text-danger"></span>
            </div>
            <div class="form-group mt-3">
                <input type="submit" value="Create" class="btn btn-primary" />
                <a asp-action="Index" class="btn btn-custom">Back to List</a>
            </div>
        </form>

PostViewModel.cs

namespace ForumApp.ViewModels
{
    public class PostViewModel
    {
        public string Title { get; set; }
        public string Content { get; set; }
    }
}

Post.cs

namespace ForumApp.Models
{
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public string UserId { get; set; }
        public ApplicationUser User { get; set; }
        public ICollection<Comment> Comments { get; set; } = [];
    }
}

Create action

        // POST: Posts/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(PostViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(User);
                var post = new Post
                {
                    Title = model.Title,
                    Content = model.Content,
                    UserId = user.Id
                };
                _context.Add(post);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(model);
        }

Even without ViewModel it was not working, adding [Bind("Title,Content")] didn't help. That's everything I receive:

null model


Solution

  • If it works with <input type="text" name="Title" class="form-control" /> but not with <input asp-for="Title" class="form-control" />, it may be because you didn't add tag helpers to your project. Check if you have a file called _ViewImports.cshtml in your Views folder with the following content:

    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers