在 http 发布 MVC 4 后未显示模型错误

本文关键字:显示 模型 错误 http 发布 MVC | 更新日期: 2023-09-27 18:33:42

我正在验证日期输入服务器端,并在用户输入无效时添加ModelError。以下是我的代码

public ActionResult EditOffer()
    {
        var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
        using (joyryde_storeEntities context = new joyryde_storeEntities())
        {
            var objOffer = context.tbl_offer.Where(x => x.LNG_OFFER_ID == offerID).FirstOrDefault();
            ViewBag.OfferID = offerID;
            ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
            ViewBag.ActionToPerform = "Edit";
            if (System.IO.File.Exists(Server.MapPath(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID))))
            {
                objOffer.TXT_OFFER_SMALL_PATH = string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID);
            }
            return View("AddOffer", objOffer);
        }       
    }
    [HttpPost]
    public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
    {
        if (ModelState.IsValid)
        {
            using (joyryde_storeEntities context = new joyryde_storeEntities())
            {
                var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
                if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
                {
                    // My Code 
                    return RedirectToAction("AllOffers", "Store");
                }
                else
                {
                    ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
                    if (Edit != null)
                    {
                        return RedirectToAction("EditOffer");
                    }
                    else
                    {
                        return RedirectToAction("AddOffer");
                    }
                }
            }
        }
        else
        {
            return RedirectToAction("EditOffer");
        }

视图

 <div class="panel-body container-fluid">
          @using (Html.BeginForm("EditOffer", "Store", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" , id="offerForm"}))
            {
              @Html.AntiForgeryToken();
              @Html.ValidationSummary(true);
                <div class="form-group">
                    <label class="col-sm-3 control-label">Offer Title</label>
                    <div class="col-sm-6">
                        @Html.TextBoxFor(model => model.TXT_OFFER_TITLE, new { @class = "form-control", placeholder = "Offer Title", autocomplete = "off", name = "title" })
                        @Html.ValidationMessageFor(model => model.TXT_OFFER_TITLE, "", new { @class = "text-danger" })                           
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 control-label">Offer Banner</label>
                    <div class="col-sm-9">
                        <div class="image-container" style=" border: 1px solid #ccc; display: table;position:relative">
                            <a href="#editimage" data-toggle="modal" class="btn btn-sm btn-icon btn-inverse btn-round btn-image-edit" data-toggle="tooltip" data-original-title="Edit">
                                <i class="icon wb-pencil" aria-hidden="true"></i>
                            </a>
                            <div class="img-preview preview-lg">
                                <img id="image_upload_preview" src="@Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="width:100%" alt="your image" />
                            </div>
                        </div>
                        <div class="input-group-file" style="margin-top:5px">
                            @Html.TextBoxFor(modal => modal.TXT_OFFER_SMALL_PATH, new { @class = "hide", @readonly = "true", width = "0", id = "filePath" })
                            @Html.ValidationMessageFor(modal => modal.TXT_OFFER_SMALL_PATH, "", new { @class = "text-danger" })
                            <span class="">
                                <span class="btn btn-success btn-small btn-file">
                                    Upload Image <i class="icon wb-upload" aria-hidden="true"></i>
                                    <input type="file" name="files" accept="image/*" multiple="" id="fileupload" onchange="showimagepreview(this)">
                                </span>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 control-label">Offer Detail </label>
                    <div class="col-sm-6">
                        @Html.TextAreaFor(model => model.TXT_OFFER_TEXT, new { @class = "form-control", placeholder = "Offer Text", autocomplete = "off", name = "text" })
                        @Html.ValidationMessageFor(model => model.TXT_OFFER_TEXT, "", new { @class = "text-danger" })                            
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 control-label">Valid For</label>
                    <div class="col-sm-4">
                        <div class="input-daterange" data-plugin="datepicker">
                            <div class="input-group">
                                <span class="input-group-addon">
                                    <i class="icon wb-calendar" aria-hidden="true"></i>
                                </span>
                                @Html.TextBoxFor(model => model.DAT_START_OFFER, "{0:dd MMMM yyyy}", new { @class = "form-control from_date", placeholder = "Start Date", autocomplete = "off", name = "start" })                                    
                                @Html.ValidationMessageFor(model => model.DAT_START_OFFER, "", new { @class = "text-danger" })                                    
                            </div>
                            <div class="input-group">
                                <span class="input-group-addon">to</span>
                                @Html.TextBoxFor(model => model.DAT_END_OFFER, "{0:dd MMMM yyyy}", new { @class = "form-control to_date", placeholder = "End Date", autocomplete = "off", name = "end" })
                                @Html.ValidationMessageFor(model => model.DAT_END_OFFER, "", new { @class = "text-danger" })                                                                       
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 control-label">Is Premium</label>
                    <div class="col-sm-4">
                        <div class="radio-custom radio-default radio-inline">
                            @Html.RadioButtonFor(model => model.INT_IS_PRIME, 1, new { @id = "ispremiumYes", name = "ispremium", @checked = "checked" })                             
                            <label for="ispremiumYes">Yes</label>
                        </div>
                        <div class="radio-custom radio-default radio-inline">
                            @Html.RadioButtonFor(model => model.INT_IS_PRIME, 0, new { @id = "ispremiumNo", name = "ispremium", })                                                               
                            <label for="ispremiumNo">No</label>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-6 col-sm-offset-3">
                        <button type="submit" name="@ViewBag.ActionToPerform" class="btn btn-primary">Submit </button>
                        <button type="reset" class="btn btn-default btn-outline">Reset</button>
                    </div>
                </div>
                @Html.Hidden("cropWidth", new { id = "cropWidth" })                             
                @Html.Hidden("cropHeight", new { id = "cropHeight" })
                @Html.Hidden("cropPointX", new { id = "cropPointX" })
                @Html.Hidden("cropPointY", new { id = "cropPointY" })
                @Html.Hidden("ImgSrc", new { id = "ImgSrc" })
          }
            <div class="modal fade" id="editimage" aria-labelledby="modalLabel" role="dialog" tabindex="-1">
                <div class="modal-dialog" role="document" style="width:1024px;height:768px">
                    <div class="modal-content ">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="modalLabel">Crop the image</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-sm-9">
                                    <div class="cropper text-center">
                                        <img id="image" src="@Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="max-width:730px;" alt="Picture">
                                    </div>
                                </div>
                                <div class="col-sm-3">
                                    <div class="docs-preview clearfix">
                                        <div class="img-preview preview-lg"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

但是模态误差没有显示在视图中。可能是什么原因?

在 http 发布 MVC 4 后未显示模型错误

当您设置模型错误时,请使用 RedirectToAction,这意味着您加载新页面,签入调试,然后您的代码返回到 GET 方法并重新加载所有内容。您必须返回带有模型的视图。

ModelState.AddModelError("DAT_START_OFFER", "Date Not Available");
if (Edit != null)
{
    return View(modal); //if your model is object named modal
}
由于

重定向到操作,您没有看到任何错误。您应该使用"查看"方法。例如,您可以只编写return EditOffer()

如果您

使用return RedirectToAction("EditOffer");则不会显示错误,它将重定向到public ActionResult EditOffer(){}操作方法,将显示[HttpGet]
要纠正此错误,您应该使用View()方法。像return View();一样,它将错误返回到"发布的表单数据"页面。

    [HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
    if (ModelState.IsValid)
    {
        using (joyryde_storeEntities context = new joyryde_storeEntities())
        {
            var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
            if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
            {
                // My Code 
                return RedirectToAction("AllOffers", "Store");
            }
            else
            {
                ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
                if (Edit != null)
                {
                    return View(modal);
                }
                else
                {
                    return RedirectToAction("AddOffer");
                }
            }
        }
    }
    else
    {
        ViewBag.OfferID = Here give the office id;
        ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
        ViewBag.ActionToPerform = "Edit";
        ModelState.AddModelError("","Your Error Message"); // Here i am adding Modal Error For Date
        return View(modal);
    }
}