模型绑定后收到 null

问题描述 投票:0回答:1

模型绑定后我收到带有空值的变量。我不知道为什么,有人可以解释一下出了什么问题吗?谢谢。 表单提交后,标题为空,内容为空。

创建.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; } = [];
    }
}

创建动作

        // 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);
        }

即使没有 ViewModel 它也无法工作,添加 [Bind("Title,Content")] 也没有帮助。这就是我收到的所有内容:空模型

asp.net .net asp.net-core model-binding
1个回答
0
投票

如果它适用于

<input type="text" name="Title" class="form-control" />
但不适用于
<input asp-for="Title" class="form-control" />
,则可能是因为您没有将标签助手添加到项目中。检查您的
_ViewImports.cshtml
文件夹中是否有一个名为
Views
的文件,其中包含以下内容:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
© www.soinside.com 2019 - 2024. All rights reserved.