在Http Post MVC 4之后没有显示模型错误

时间:2016-02-08 09:12:15

标签: c# asp.net-mvc validation addmodelerror

我正在验证日期输入服务器端,如果用户输入无效,则添加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>

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

由于RedirectToAction,您没有看到任何错误。你应该使用&#34; View&#34;方法。例如,您只需撰写return EditOffer()

即可

答案 2 :(得分:0)

如果您使用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);
    }
}