简体   繁体   English

Http Post MVC 4后未显示模型错误

[英]Model Error Not Showing after Http Post MVC 4

I am validating date input server side and adding ModelError if user input is invalid. 我正在验证日期输入服务器端,如果用户输入无效,则添加ModelError Following is my code 以下是我的代码

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");
        }

View 视图

 <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>

But Modal Error is not showing on view. 但是模态错误未显示在视图上。 What could be the cause ? 可能是什么原因 ?

When you set your model error then you use RedirectToAction, what mean that you load new page, check in your debug, after that your code go back to GET method and everything is reloaded. 当您设置模型错误时,您将使用RedirectToAction,这意味着您加载新页面,签入调试,然后代码返回GET方法并重新加载所有内容。 You have to return your View with model. 您必须返回带有模型的视图。

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

You didn't see any error because of RedirectToAction. 由于RedirectToAction,您没有看到任何错误。 You should use the "View" method. 您应该使用“查看”方法。 For example you can just write return EditOffer() 例如,您可以编写return EditOffer()

If you use return RedirectToAction("EditOffer"); 如果使用return RedirectToAction("EditOffer"); the error will not been show it will be redirect to public ActionResult EditOffer(){} Action method, the [HttpGet] will be shown. 该错误将不会显示,它将被重定向到public ActionResult EditOffer(){} Action方法,将显示[HttpGet]
To rectify this error, you should use View() method. 要纠正此错误,您应该使用View()方法。 like return View(); return View(); it return the error to the form data posted page. 它将错误返回到表单数据发布页面。

    [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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM