为啥在 MVC 项目中返回的表单值为空?

Posted

技术标签:

【中文标题】为啥在 MVC 项目中返回的表单值为空?【英文标题】:Why returened values of form are null in MVC project?为什么在 MVC 项目中返回的表单值为空? 【发布时间】:2016-03-27 05:55:24 【问题描述】:

我尝试更新记录。我在此视图中使用验证,但总是

ModelState.IsValid = false

我在网上搜索,发现我应该用这段代码检查错误:

 var errors = ModelState.Values.SelectMany(v => v.Errors);

现在我不明白这是什么问题? 在此图像中,您可以看到所有参数都为空。

请指教。 查看:

    @model TravelEnterAdminTemplate.Models.LG.ResturantModel
@
    ViewBag.Title = "EditRestaurant";
    Layout = "~/Views/Shared/_Layout.cshtml";

@*fck Editor*@
<script type="text/javascript" src="@Url.Content("~/Content/Adminex/js/fckEditor/fckeditor.js")"></script>
<script type="text/javascript">
    window.onload = function () 
        var sBasePath = '@Url.Content("~/Content/Adminex/js/fckeditor/")';
        var oFCKeditor = new FCKeditor('Restaurants_Description');
        oFCKeditor.BasePath = sBasePath;
        oFCKeditor.Height = 450;
        oFCKeditor.Width = 800;
        oFCKeditor.ReplaceTextarea();
        //----------------------DescriptionEn---------------------
        var oFCKeditorEn = new FCKeditor('Restaurants_DescriptionEn');
        oFCKeditorEn.BasePath = sBasePath;
        oFCKeditorEn.Height = 450;
        oFCKeditorEn.Width = 800;
        oFCKeditorEn.ReplaceTextarea();
    
</script>
<div class="container">
    <h4>ویرایش رستوران</h4>
    <hr />

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

        <div class="form-horizontal">


            @Html.ValidationSummary(true, "", new  @class = "text-danger" )


            @Html.HiddenFor(model => model.Restaurants.id)



            <div class="row">
                <div class="col-md-4  pull-right">
                    @Html.LabelFor(model => model.Restaurants.RestaurantName, htmlAttributes: new  @lablefor = "RestaurantName" )


                    @Html.EditorFor(model => model.Restaurants.RestaurantName, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">@Html.ValidationMessageFor(model => model.Restaurants.RestaurantName, "", new  @class = "text-danger" )</div>
            </div>

            <div class="row">
                <div class="col-md-7  pull-right">
                    @Html.LabelFor(model => model.Restaurants.Address, htmlAttributes: new  @lablefor = "Address" )


                    @Html.EditorFor(model => model.Restaurants.Address, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">@Html.ValidationMessageFor(model => model.Restaurants.Address, "", new  @class = "text-danger" )</div>
            </div>

            <div class="row">
                <div class="col-md-2 pull-right">
                    @Html.LabelFor(model => model.Restaurants.City.Country.NameFa, htmlAttributes: new  @lablefor = "CountryId" )
                    @Html.DropDownList("CountryId", null, new  @class = "form-control" )
                </div>
            </div>

            <div class="row">
                <div class="col-md-2 pull-right">
                    <div>
                        @Html.LabelFor(model => model.Restaurants.City.NameFA, htmlAttributes: new  @lablefor = "CityId" )
                        @Html.DropDownList("CityId", null, new  @class = "form-control" )
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-2  pull-right">
                    @Html.LabelFor(model => model.Restaurants.Tell, htmlAttributes: new  @lablefor = "Tell" )
                    @Html.EditorFor(model => model.Restaurants.Tell, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">@Html.ValidationMessageFor(model => model.Restaurants.Tell, "", new  @class = "text-danger" )</div>
            </div>

            <div class="row">
                <div class="col-md-4  pull-right">
                    @Html.LabelFor(model => model.Restaurants.Title, htmlAttributes: new  @lablefor = "Title" )


                    @Html.EditorFor(model => model.Restaurants.Title, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">
                    @Html.ValidationMessageFor(model => model.Restaurants.Title, "", new  @class = "text-danger" )
                </div>
            </div>

            <div class="row">
                <div class="col-md-3  pull-right">
                    @Html.LabelFor(model => model.Restaurants.InsertDate, htmlAttributes: new  @lablefor = "InsertDate" )


                    @Html.EditorFor(model => model.Restaurants.InsertDate, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">@Html.ValidationMessageFor(model => model.Restaurants.InsertDate, "", new  @class = "text-danger" )</div>
            </div>

            <div class="row">
                <div class="col-md-5  pull-right">
                    @Html.LabelFor(model => model.Restaurants.Summary, htmlAttributes: new  @lablefor = "Summary" )


                    @Html.EditorFor(model => model.Restaurants.Summary, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">
                    @Html.ValidationMessageFor(model => model.Restaurants.Summary, "", new  @class = "text-danger" )
                </div>
            </div>

            <div class="row">
                <div class="col-md-8  pull-right">
                    @Html.LabelFor(model => model.Restaurants.Description, htmlAttributes: new  @lablefor = "Description" )


                    @Html.EditorFor(model => model.Restaurants.Description, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">@Html.ValidationMessageFor(model => model.Restaurants.Description, "", new  @class = "text-danger" )</div>
            </div>

            <div class="row">
                <div class="col-md-3  pull-right">
                    @Html.LabelFor(model => model.Restaurants.LocationX, htmlAttributes: new  @lablefor = "LocationX" )


                    @Html.EditorFor(model => model.Restaurants.LocationX, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">
                    @Html.ValidationMessageFor(model => model.Restaurants.LocationX, "", new  @class = "text-danger" )
                </div>
            </div>

            <div class="row">
                <div class="col-md-3  pull-right">
                    @Html.LabelFor(model => model.Restaurants.LocationY, htmlAttributes: new  @lablefor = "LocationY" )


                    @Html.EditorFor(model => model.Restaurants.LocationY, new  htmlAttributes = new  @class = "form-control"  )

                </div>
                <div class="col-md-4 pull-right">@Html.ValidationMessageFor(model => model.Restaurants.LocationY, "", new  @class = "text-danger" )</div>
            </div>

            <div class="row">
                <div class="col-md-3  pull-right">
                    @Html.LabelFor(model => model.Restaurants.Website, htmlAttributes: new  @lablefor = "Website" )


                    @Html.EditorFor(model => model.Restaurants.Website, new  htmlAttributes = new  @class = "form-control website"  )

                </div>
                <div class="col-md-4 pull-right">@Html.ValidationMessageFor(model => model.Restaurants.Website, "", new  @class = "text-danger" )</div>
            </div>
            <div class="row">

                <div class="col-md-5  pull-right">
                    <div class="checkbox">
                        @Html.LabelFor(model => model.Restaurants.IsActive, htmlAttributes: new  @lablefor = "IsActive" )
                        @Html.EditorFor(model => model.Restaurants.IsActive)

                    </div>
                    <div class="col-md-4 pull-right">
                        @Html.ValidationMessageFor(model => model.Restaurants.IsActive, "", new  @class = "text-danger" )
                    </div>
                </div>
            </div>
            @*-------------------------------------------------------------------------------------*@
            <fieldset dir="ltr" class="fieldsetEn">
                <legend>English Content</legend>
                <div class="row">
                    <div class="col-md-5">
                        <div class="checkbox checkboxEn">
                            @Html.LabelFor(model => model.Restaurants.IsEnglish, htmlAttributes: new  @Labelfor = "IsEnglish" )
                            @Html.EditorFor(model => model.Restaurants.IsEnglish)
                        </div>
                        <div class="col-md-4 ">
                            @Html.ValidationMessageFor(model => model.Restaurants.IsEnglish, "", new  @class = "text-danger" )
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4">
                        @Html.LabelFor(model => model.Restaurants.RestaurantNameEn, htmlAttributes: new  @Labelfor = "RestaurantNameEn" )
                        @Html.EditorFor(model => model.Restaurants.RestaurantNameEn, new  htmlAttributes = new  @class = "form-control"  )
                    </div>
                    <div class="col-md-4 ">
                        @Html.ValidationMessageFor(model => model.Restaurants.RestaurantNameEn, "", new  @class = "text-danger" )
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-7">
                        @Html.LabelFor(model => model.Restaurants.AddressEn, htmlAttributes: new  @Labelfor = "AddressEn" )
                        @Html.EditorFor(model => model.Restaurants.AddressEn, new  htmlAttributes = new  @class = "form-control"  )
                    </div>
                    <div class="col-md-4 ">
                        @Html.ValidationMessageFor(model => model.Restaurants.AddressEn, "", new  @class = "text-danger" )
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4">
                        @Html.LabelFor(model => model.Restaurants.TitleEn, htmlAttributes: new  @Labelfor = "TitleEn" )
                        @Html.EditorFor(model => model.Restaurants.TitleEn, new  htmlAttributes = new  @class = "form-control"  )
                    </div>
                    <div class="col-md-4 ">
                        @Html.ValidationMessageFor(model => model.Restaurants.TitleEn, "", new  @class = "text-danger" )
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-5">
                        @Html.LabelFor(model => model.Restaurants.SummaryEn, htmlAttributes: new  @Labelfor = "" )
                        @Html.EditorFor(model => model.Restaurants.SummaryEn, new  htmlAttributes = new  @class = "form-control"  )
                    </div>
                    <div class="col-md-4 ">
                        @Html.ValidationMessageFor(model => model.Restaurants.SummaryEn, "", new  @class = "text-danger" )
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-7">
                        @Html.LabelFor(model => model.Restaurants.DescriptionEn, htmlAttributes: new  @Labelfor = "DescriptionEn" )
                        @Html.TextAreaFor(model => model.Restaurants.DescriptionEn, new  htmlAttributes = new  @class = "form-control"  )
                    </div>
                    <div class="col-md-4 ">
                        @Html.ValidationMessageFor(model => model.Restaurants.DescriptionEn, "", new  @class = "text-danger" )
                    </div>
                </div>

            </fieldset>

            @
        string path = System.Configuration.ConfigurationManager.AppSettings["ImageEdit"];
            
            <div class="row text-right">
                @foreach (var item in Model.PhotoTables)
                

                    <text>
                        <div class="col-xs-2 col-wrapper pull-right">
                            <div class="image-wrapper">
                                <img src="@Url.Content(path + item.PhotoName)"  class=" img-responsive" />
                                <img class="delimg" src="~/Content/Adminex/images/delete-icons.png" id="@item.Id"  />
                            </div>
                        </div>
                    </text>

                
            </div>

            <br />
            <br />

            <div class="row">
                <div class="col-md-4"></div>
                <div class="col-md-4">
                    <input type="submit" value="ذخیره تغییرات" class="btn btn-info btn-block" />
                </div>
                <div class="col-md-4"></div>
                </div>
        </div>
    
</div>
<script src="~/Content/Adminex/js/ajax/Restaurants_Edit.js"></script>
@section Scripts 
    @Scripts.Render("~/bundles/jqueryValidation")

型号:

    //------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TravelEnterAdminTemplate.Models.dbModel

    using System;
    using System.Collections.Generic;

    public partial class Restaurant
    
        public int id  get; set; 
        public int CityId  get; set; 
        public string RestaurantName  get; set; 
        public string Address  get; set; 
        public string Tell  get; set; 
        public string Title  get; set; 
        public System.DateTime InsertDate  get; set; 
        public string Summary  get; set; 
        public string Description  get; set; 
        public string LocationX  get; set; 
        public string LocationY  get; set; 
        public string UserId  get; set; 
        public int Visitor  get; set; 
        public bool IsActive  get; set; 
        public string Website  get; set; 
        public int CategoryId  get; set; 
        public string RestaurantNameEn  get; set; 
        public string AddressEn  get; set; 
        public string TitleEn  get; set; 
        public string SummaryEn  get; set; 
        public string DescriptionEn  get; set; 
        public Nullable<int> VisitorEn  get; set; 
        public bool IsEnglish  get; set; 

        public virtual AspNetUser AspNetUser  get; set; 
        public virtual City City  get; set; 
    

【问题讨论】:

尝试发布您的视图和视图模型代码 您视图中的模型是ResturantModel,但您的POST方法中的模型是Restaurant(它们必须相同!) 【参考方案1】:

我有时会使用这样的代码进行调试。 (凭记忆写的)

var errors = new List<KeyValuePair<string, string>();
for (int i = 0; i < ModelState.Keys.Count; i++)

     var value = ModelState.Values.ElementAt(i);
     if value.Errors.Any()
     
          foreach (var error in Value.Errors)
          
               errors.Add(new KeyValuePair<string, string>
                 (ModelState.Keys.ElementAt(i),
                  error.Message ??  error.Exception.Message);
           
      
 

这应该可以帮助您诊断导致验证错误的模型元素。

服务器端验证错误的常见原因是模型中包含不可为空的 int 或 Guid Id 字段,但视图中未包含,或者被隐藏和/或未填充。

【讨论】:

你说得对。我使用这段代码,发现 error.ErrorMessage 是我在 Mete Data 中用于验证的消息,error.Exception.Message 为 null。换句话说,表单中的所有返回值都是 null。现在如何解决这个问题? 重点是识别无效的字段,并修复问题。快速查看视图和模型表明它可能是您的 CategoryId。【参考方案2】:

这不是你发帖的方式。

您的 post 方法应该非常简单,例如:

公共异步任务发布(ModelClass someName)

所以你基本上有一个模型类。该类需要用需要引用 System.Runtime.Serialization 的 [DataContract] 进行装饰

您希望能够作为帖子的一部分发送的该类中的每个属性都需要有一个 DataMember 标记。这样,只要表单传递的名称与模型中的名称完全匹配,MVC 引擎使用的默认序列化就会启动并接受您的帖子。这尤其适用于我们使用 WebApi 时。对于纯 MVC 工作,我们不需要这些标签

始终先进行模型验证:

if (!ModelState.IsValid) 则返回错误码

模型属性上的每个验证项都需要在 ModelState 有效之前发生。

这是我几年前写的一个基本示例,也许会有所帮助:

mvc article

【讨论】:

以上是关于为啥在 MVC 项目中返回的表单值为空?的主要内容,如果未能解决你的问题,请参考以下文章

如果jsp表单元素的值为空,如何避免null出现在页面上?

mysql 为啥总是推荐使用联合索引而不是单值索引

php在提交表单之前将数据插入数据库中的值为空?

ASP .NET MVC Redirecttoaction 将参数传递给 Index 但值为空

在 MVC 5 模型中提交表单在控制器发布方法中为空 [重复]

为啥字符串值为空?