2016-03-27 4 views
-1

Я пытаюсь обновить запись й использовать проверку в этой точке зрения, но всегдаПочему возвращаемые значения формы являются нулевыми в проекте MVC?

ModelState.IsValid = ложь

Я ищу в Интернете и обнаружил, что я должен проверить ошибки с помощью этого кода:

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

enter image description here Теперь я не могу понять, что это проблема? На этом изображении вы можете увидеть, что все параметры равны нулю. enter image description here

Прошу совета. Вид:

@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)" alt="" class=" img-responsive" /> 
           <img class="delimg" src="~/Content/Adminex/images/delete-icons.png" id="@item.Id" alt="حذف تصویر" /> 
          </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; } 
    } 
} 
+0

Попробуйте разместить свое мнение и код ViewModel –

+1

модель на ваш взгляд, является 'ResturantModel' но модель ваш метод POST - «Ресторан» (они должны быть одинаковыми!) –

ответ

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, но либо не включено в представление, либо скрыто и/или не заполнено.

+0

Вы правы. Я использую этот код и обнаружил эту ошибку.ErrorMessage - это мой массаж в Mete Data для проверки и ошибки. Exception.Message имеет значение null. Другими словами, все возвращаемые значения в форме равны нулю. Теперь Как это исправить? – programmer138200

+0

Дело в том, чтобы определить недопустимое поле и исправить проблему. Быстрый взгляд на представление и модель предполагает, что это может быть ваш CategoryId. –

0

это не то, что вы публикуете, хотя.

ваш метод пост должен быть очень простой, что-то вроде:

общественного асинхронной Task Post (ModelClass SomeName)

так что вы в основном имеют класс модели. Этот класс должен быть украшен [DataContract], для которого требуется ссылка на System.Runtime.Serialization

Каждое свойство этого класса, которое вы хотите отправить как часть сообщения, должно иметь тег DataMember Это. Таким образом, сериализация по умолчанию, используемая движком MVC, будет включать и принимать ваш пост до тех пор, пока имена, прошедшие форму, точно совпадают с именами в модели. Это особенно важно, когда мы работаем с WebApi. Для чистого MVC работы нам не нужны эти теги

Всегда делать модели проверки первого: (! ModelState.IsValid)

если затем возвращает код ошибки

каждый пункт проверки вас на свойствах модели должно произойти до того, как ModelState будет действительным.

Вот простой пример, который я написал несколько лет назад, может быть, это поможет:

mvc article