• 1399/01/22

مشکل در اکشن post با شرط ModelState.IsValid :

سلام وقت بخیر

کد های ویو :

@using DataLayer
@model DataLayer.Contents
@{
    ViewBag.Title = "ثبت مطلب جدید";
}
@section css
{
    <link href="@Url.Content("~/Content/bower_components/select2/dist/css/select2.min.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/plugins/iCheck/all.css")" rel="stylesheet" type="text/css" />
}
@using (Html.BeginForm("Create", "Contents", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="row">
        <div class="col-md-6">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">مشخصات مطلب</h3>
                </div>
                <div class="box-body">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Title, "", new { @class = "help-block" })
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Description, "", new { @class = "help-block" })
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Keywords, htmlAttributes: new { @class = "control-label" })
                        <small>(کلمات کلیدی را با کاما "،" از هم جدا کنید!)</small>
                        @Html.EditorFor(model => model.Keywords, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Keywords, "", new { @class = "help-block" })
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">دسته بندی ها</h3>
                </div>
                <div class="box-body">
                    @if (ViewBag.ErrorSelectedGroup == true)
                    {
                        <div class="alert alert-danger alert-dismissible">
                            <button type="button" class="close pull-left" data-dismiss="alert" aria-hidden="true">&times;</button>
                            <h4><i class="icon fa fa-warning"></i> توجه</h4>
                            لطفا دسته بندی های مطلب را انتخاب کنید
                        </div>
                    }
                    @{
                        List<ContentsGroups> groups = ViewBag.Groups;
                        <ul>
                            @foreach (var group in groups.Where(g => g.ParentId == null))
                            {
                                <li>
                                    <input type="checkbox" name="selectedGroups" value="@group.GroupId" /> <span>@group.GroupTitle</span>
                                    @if (groups.Any(g => g.ParentId == group.GroupId))
                                    {
                                        <ul>
                                            @foreach (var subGroup in groups.Where(g => g.ParentId == group.GroupId))
                                            {
                                                <li>
                                                    <input type="checkbox" name="selectedGroups" value="@subGroup.GroupId" /> <span>@subGroup.GroupTitle</span>
                                                </li>
                                            }
                                        </ul>
                                    }
                                </li>
                            }
                        </ul>
                    }
                </div>
            </div>
        </div>
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-header with-border">
                    @Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "box-title", Style = "font-weight:500" })
                </div>
                <div class="box-body">
                    <div class="form-group pad">
                        @Html.EditorFor(model => model.Text, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Text, "", new { @class = "help-block" })
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-5">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">تصویر مطلب</h3>
                </div>
                <div class="box-body">
                    <img src="~/Uploads/Contents/noimg.jpg" class="img-thumbnail" style="max-width: 50%" id="imgPreview" />
                    <br /><br />
                    <div class="form-group">
                        <input type="file" name="ImgUp" id="ImgUp" />
                        @Html.ValidationMessageFor(model => model.ImageName, "", new { @class = "help-block" })
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-7">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">تکمیل</h3>
                </div>
                <div class="box-body">
                    <div class="form-group">
                        <div class="checkbox">
                            @Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label" })
                            @Html.EditorFor(model => model.IsActive, new { htmlAttributes = new { @class = "minimal" } })
                            @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "help-block" })
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="checkbox">
                            @Html.LabelFor(model => model.IsVip, htmlAttributes: new { @class = "control-label" })
                            @Html.EditorFor(model => model.IsVip, new { htmlAttributes = new { @class = "minimal" } })
                            @Html.ValidationMessageFor(model => model.IsVip, "", new { @class = "help-block" })
                        </div>
                    </div>
                </div>
                <div class="box-footer">
                    <input type="submit" value="ثبت و ذخیره" class="btn btn-success" />
                </div>
            </div>
        </div>
    </div>
}
@section Scripts {
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="@Url.Content("~/Content/bower_components/select2/dist/js/select2.full.min.js")"></script>
    <script src="@Url.Content("~/Content/plugins/iCheck/icheck.min.js")"></script>
    <script>
        $(function () {
            $('.select2').select2();
            $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
                checkboxClass: 'icheckbox_minimal-blue',
                radioClass: 'iradio_minimal-blue'
            });
        });
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#imgPreview').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        $("#ImgUp").change(function () {
            readURL(this);
        });
    </script>
    <script src="/ckeditor/ckeditor.js"></script>
    <script src="/ckeditor/adapters/jquery.js"></script>
    <script>
        $(function () {
            $('#Text1').ckeditor();
        });
    </script>
}

 

کد های کنترلر :

public ActionResult Create()
        {
            ViewBag.Groups = db.ContentsGroups.ToList();
            return View();
        }

        // POST: Admin/Contents/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ContentId,Title,Description,Keywords,ImageName,Text,CreateDate,UpdateDate,IsActive,IsVip")] Contents contents, List<int> selectedGroups, HttpPostedFileBase ImgUp, string Keywords)
        {
            if (ModelState.IsValid)
            {
                if (selectedGroups == null)
                {
                    ViewBag.ErrorSelectedGroup = true;
                    ViewBag.Groups = db.ContentsGroups.ToList();
                    return View(contents);
                }
                contents.ImageName = "noimg.jpg";
                if (ImgUp != null && ImgUp.IsImage())
                {
                    contents.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(ImgUp.FileName);
                    ImgUp.SaveAs(Server.MapPath("/Uploads/Contents/" + contents.ImageName));
                    ImageResizer img = new ImageResizer();
                    img.Resize(Server.MapPath("/Uploads/Contents/" + contents.ImageName),
                        Server.MapPath("/Uploads/Contents/Thumb/" + contents.ImageName));
                }
                contents.CreateDate = DateTime.Now;
                contents.UpdateDate = DateTime.Now;
                db.Contents.Add(contents);
                foreach (int selectedGroup in selectedGroups)
                {
                    db.ContentsSelectedGroups.Add(new ContentsSelectedGroups()
                    {
                        ContentId = contents.ContentId,
                        GroupId = selectedGroup
                    });
                }
                if (!string.IsNullOrEmpty(Keywords))
                {
                    string[] tag = Keywords.Split('،');
                    foreach (string t in tag)
                    {
                        db.ContentsTags.Add(new ContentsTags()
                        {
                            ContentId = contents.ContentId,
                            TagTitle = t.Trim()
                        });
                    }
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Groups = db.ContentsGroups.ToList();
            return View(contents);
        }

 

 

شرح مشکل :

زمانی که روی submit کلیک میشه، اصلا وارد شرط ModelState.IsValid نمیشه و مستقیم return View(contents) رو برمیگردونه، درحالی که تمام مقادیر پر شده و خطای اعتبارسنجی نباید وجود داشته باشه! و اینکه در View هم متن خطایی نمایش نمیده که متوجه بشم کدام یک از اعتبارسنجی ها انجام نشده!

اما زمانی که شرط ModelState.IsValid رو برمیدارم و کد هارو مستقیم می نویسم به درستی کار میکنه!

کد رو در هر دو حالت (با شرط و بدون شرط) تریس کردم؛

وقتی شرط وجود داشته باشه ModelState.IsValid رو false برمیگردونه...
وقتی شرط وجود نداشته باشه تمام مقادیر به درستی پر میشه و مطلب ثبت میشه (در بانک هم کامله)

مشکل از چی میتونه باشه؟! چرا نمیتونم از شرط ModelState.IsValid استفاده کنم؟

  • 1399/01/22
  • ساعت 19:24

سلام 

مقادیر داخل مدل را بررسی کنید 

وقتی valid نمیشه یعنی مشکلی وجود داره 


  • 1399/01/22
  • ساعت 19:47

درواقع مشکل از این بود که در بانک CreateDate و UpdateDate رو Null پذیر کرده بودم، و در مدل هم Nullable بود!

وقتی که تیک AllowNull رو برداشتم و دیتابیس و مدل رو Update کردم این مشکل حل شد

اما چرا؟!
قاعدتا نباید اینجوری باشه! باید بتونیم نال پذیر کنیم...


  • 1399/01/22
  • ساعت 19:52

بله 

احتمالا مدل آپدیت نشده بوده 


logo-enamadlogo-samandehi