modelstate.isvalid false,因为该项始终为null

时间:2018-04-26 10:43:04

标签: asp.net

所以我尝试制作一个asp.net核心2(视觉工作室2017)。试图为主银行制作一个简单的视图,新建,编辑和删除。我已经成功完成了视图并创建了新视图,但现在我被困在编辑部分。因此,当用户单击编辑时,我打开新窗口并显示要编辑的详细信息,然后当他们单击保存按钮时,我保存了值(如创建新建时)。就是这么简单。但由于某种原因,用于编辑的modelstate.isvalid总是为false,当我尝试调试时,我发现所有项都返回null(它们都显示在视图上),但主键除外。请帮助我做错了:

班级:


        public class MsBank
        {
            [Required(ErrorMessage = "Required.")]
            [RegularExpression(@"\b[A-Z0-9]{1,}\b", ErrorMessage = "Must Be Uppercase")]
            public string BankCode { get; set; }

            [Required(ErrorMessage = "Required.")]
            public string BankName { get; set; }

            public string BankBranch { get; set; }

            private SqlConnection con;
            private void connection()
            {
                PrjCommon dbhandle = new PrjCommon();
                con = new SqlConnection(dbhandle.GetSetting());
            }

    public bool AddBank(List smodel)
    {
        connection();
        SqlCommand cmd = new SqlCommand("SaveMsBank", con);
        cmd.CommandType = CommandType.StoredProcedure;

        foreach (var item in smodel) { 
        cmd.Parameters.AddWithValue("@BankCode", item.BankCode);
        cmd.Parameters.AddWithValue("@BankName", item.BankName);
        cmd.Parameters.AddWithValue("@BankBranch", item.BankBranch);
        cmd.Parameters.AddWithValue("@LastUpdatedBy", "Me");
        cmd.Parameters.AddWithValue("@LastUpdatedFromModule", "NET");
        }
        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();

        if (i >= 1)
            return true;
        else
            return false;
    }
}
    }

观点:


     @model List[MsBank]
    @{
        ViewData["Title"] = "Edit";
    }

    @using (Html.BeginForm())
        {
    @Html.AntiForgeryToken()

    
        
            

            @foreach (var item in Model) {
            
                Code :
                @Html.EditorFor(model => item.BankCode, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => item.BankCode, "", new { @class = "text-danger" })
            
            
                Name :
                @Html.EditorFor(model => item.BankName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => item.BankName, "", new { @class = "text-danger" })
            
            
                Branch :
                @Html.EditorFor(model => item.BankBranch, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => item.BankBranch, "", new { @class = "text-danger" })
            
            
                
            
            }
        
    
    }
    @ViewBag.Message
    
        @Html.ActionLink("Back to List", "Index")
    

    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

和控制器:



       public ActionResult Edit(string BankCode)
        {
            MsBank ms = new MsBank();
            ModelState.Clear();
            return View(ms.GetData(BankCode));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(string BankCode,List smodel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (smodel.Count > 0)
                    {
                        MsBank ms = new MsBank();
                        if (ms.AddBank(smodel))
                        {
                            ViewBag.Message = "Bank Edited Successfully";
                            ModelState.Clear();
                        }
                        return RedirectToAction("Index");
                    }
                    else { ViewBag.Message = "Empty Record"; }
                }
                return View(smodel);
            }
            catch (Exception e)
            {
                ViewBag.Message = e.ToString();
                return View(smodel);
            }
        }

所以,为了使它更清楚,上面的modelstate.isvalid返回false(当我发现调试时),因为bankname是无效的,因为它是null,所以bankbranch也是null

1 个答案:

答案 0 :(得分:0)

问题在我看来,你的视图正在接收一个msnumerable的msbank @model IEnumerable [WBMS.Models.MsBank],当它真的只是在它的单个实例中。然后,您将遍历模型,这会将编辑视图中的表单字段名称从BankCode更改为item_BankCode,这就是您在这些值上返回null的原因。

尝试将修改视图更改为:

@model WebApplication2.Models.MsBank

@{
    ViewData["Title"] = "Edit";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    @:Code:
    @Html.EditorFor(model => model.BankCode, new { htmlAttributes = new { 
    @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.BankCode, "", new
    {
          @class = "text-danger"
    })

    @:Name:
    @Html.EditorFor(model => model.BankName, new { htmlAttributes = new { 
    @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.BankName, "", new
    {
        @class = "text-danger"
    })

    @:Branch:
    @Html.EditorFor(model => model.BankBranch, new { htmlAttributes = new { 
    @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.BankBranch, "", new
    {
        @class = "text-danger"
    })

    <button type="submit">Submit</button>
}

@ViewBag.Message

@Html.ActionLink("Back to List", "Index")