Model Error Not Showing after Http Post MVC 4

295 views Asked by At

I am validating date input server side and adding ModelError if user input is invalid. 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 ?

3

There are 3 answers

4
Sousuke On BEST ANSWER

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. 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
}
0
Marcin Iwanowski On

You didn't see any error because of RedirectToAction. You should use the "View" method. For example you can just write return EditOffer()

0
anand On

If you use return RedirectToAction("EditOffer"); the error will not been show it will be redirect to public ActionResult EditOffer(){} Action method, the [HttpGet] will be shown.
To rectify this error, you should use View() method. like 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);
    }
}