Asp.Net Core 2绑定对象为null

时间:2018-04-11 00:08:14

标签: c# asp.net-core-2.0 razor-pages

当我提交表单时,ModelValidation.IsValid为true,但我使用[BindProperty]的对象为null。

PageModel

我在[BindProperty]媒体资源上有public Group Group {get; private set}标记。

OnGetAsync(int? Id)方法中,我使用.FindAsync(Id)查找群组并填写表单。这很好用:))

我的理解是OnPostAsync()应该作为BindProperty注释的结果自动填充Group对象。但是,一旦我发布ModelState为Valid,但Group对象为null。我该如何解决这个问题?

using xxx.ReportGroups.Data;
using xxx.ReportGroups.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace xxx.ReportGroups.Pages
{

    public class GroupEditModel : PageModel
    {
        private readonly ApplicationDbContext _db;

        public GroupEditModel(ApplicationDbContext db)
        {
            _db = db;
        }

        [BindProperty]
        public string ErrorMessage { get; private set; }

        [BindProperty]
        public Group Group { get; private set; }

        public IList<Group> ParentGroups { get; private set; }

        public IList<Tier> Tiers { get; private set; }

        public IList<GroupType> GroupTypes { get; private set; }


        //public async Task<IActionResult> OnGetAsync(int? id)
        // Snip.  It works fine

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<dl>");
                foreach (var modelStateKey in ViewData.ModelState.Keys)
                {
                    var modelStateVal = ViewData.ModelState[modelStateKey];
                    foreach (var error in modelStateVal.Errors)
                    {
                        var key = modelStateKey;
                        var errorMessage = error.ErrorMessage;
                        var exception = error.Exception;
                        // You may log the errors if you want
                        sb.Append($"<dt>Key <span class=\"error-hilight\">{key}</span></dt><dd>{errorMessage}<br>{exception}</dd>{Environment.NewLine}");
                    }
                }
                sb.Append("</dl>");
                ErrorMessage = sb.ToString();
                return Page();
            }

            _db.Attach(Group).State = EntityState.Modified;

            try
            {
                await _db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                ErrorMessage = $"Group {Group.Id} not found!";
            }
            return RedirectToPage();
        }

        public async Task<IActionResult> OnPostDeleteAsync(int id)
        {
            var contact = await _db.Groups.FindAsync(id);
            if (contact != null)
            {
                _db.Groups.Remove(contact);
                await _db.SaveChangesAsync();
            }
            return RedirectToPage();
        }
    }
}

下面列出的是.cshtml页面。它是一个编辑页面,用于更新现有对象的详细信息。它显示当前值,然后在下面有一个表格来修改值。

添加了隐藏值以确保我设置了对象的[Required]属性,但这并没有解决问题。

@page "{id:int?}"
@model GroupEditModel

@{
    ViewData["Title"] = "Edit Group";
}
<h2><i class="fas fa-users"></i> 
    @ViewData["Title"] - 
    @Model.Group.Id
    @Model.Group.Name</h2>

@if(Model.ErrorMessage != null)
{
    <div class="error">
        @(new HtmlString(Model.ErrorMessage))
    </div>

}

    <form method="post">
        <div asp-validation-summary="All"></div>
        <input asp-for="Group.Id" type="hidden" />
        <input asp-for="Group.OrgCode" type="hidden" />
        <input asp-for="Group.GroupTypeId" type="hidden" />
        <input asp-for="Group.ExcludeFromAlertStats" type="hidden" />

        <div class="form-static">
            <h3>Current Values</h3>
            <fieldset>
                <label>Name</label>
                <span class="readonly">@Model.Group.Name</span>
            </fieldset>

            <fieldset>
                <label>Parent</label>
                <span class="readonly">@Model.Group.Parent.Name</span>
            </fieldset>

            <fieldset>
                <label>Tier</label>
                <span class="readonly">@Model.Group.Tier.Id</span>  <span class="readonly">@Model.Group.Tier.Name</span>
            </fieldset>

            <fieldset>
                <label>Group Type</label>
                <span class="readonly">@Model.Group.GroupType.Name</span>
                <i class="fas fa-lock" title="This property requires admin rights to change"></i>
            </fieldset>

            <fieldset>
                <label asp-for="Group.OrgCode">Org Code</label>
                <span class="readonly">@Model.Group.OrgCode</span>
                <i class="fas fa-lock" title="This property requires admin rights to change"></i>
            </fieldset>
        </div>

        <div class="form-edit">
            <h3>Edit Values</h3>
            <fieldset>
                <label for="Group.Name">Name</label>
                <input asp-for="Group.Name" />
                <span asp-validation-for="Group.Name"></span>
            </fieldset>

            <fieldset>
                <label for="Group.ParentGroupId">Parent</label>
                <select asp-for="Group.ParentGroupId">
                    @foreach (Group parent in Model.ParentGroups)
                {
                    <option value="@parent.Id">@parent.Name</option>
            }
                </select>
            </fieldset>

            <fieldset>
                <label for="Group.TierId">Tier</label>
                <select asp-for="Group.TierId">
                    @foreach (Tier tier in Model.Tiers)
                {
                    <option value="@tier.Id">@tier.Name</option>
            }
                </select>
            </fieldset>

            <fieldset>
                <input type="submit" />
            </fieldset>
        </div>
    </form>


<h2><i class="fas fa-trash-alt"></i> Delete Group</h2>
<form method="post">
    <div class="form-delete">
        <fieldset>
            <i class="fas fa-trash-alt" style="color:red"></i>
            <button type="submit" asp-page="/App/GroupEdit" asp-page-handler="delete"
                    asp-route-id="@Model.Group.Id">
                Delete
            </button>
        </fieldset>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

您必须公开属性设置器。