Validate Bootstrap Modal PopUp using Ajax.BeginForm in ASP.Net MVC

Last Reply one year ago By bigbear

Posted one year ago

The modal opens then closes and in a new window the controls of mymodal opens with the validation that should have opened in the modal

<input type="button" class="openModal btn btn-danger" data-quoteid="@Model.ListQuotes[i].QuoteID" value="Edit" />
@using (Ajax.BeginForm("UpdateServiceTables", "Service", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "modal-body"  }))
{
    @Html.AntiForgeryToken()
    <div class="modal fade" id="modalInnerSQ" tabindex="-1" role="dialog" aria-labelledby="lblSQmodal" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">                
                <div class="modal-header">
                    <h4 class="modal-title"><b>Service Quote Details</b></h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    @Html.HiddenFor(x => x.ServiceVM.QuoteID)
                    @Html.HiddenFor(x => x.ServiceVM.CustomerID)
                    @Html.HiddenFor(x => x.ServiceVM.ContactID)
                    @Html.HiddenFor(x => x.ServiceVM.EmpID)
 
                    <div class="form-group">
                        @Html.LabelFor(x => x.ServiceVM.CustomerName, htmlAttributes: new { @class = "control-label col-3" })
                        <div class="col-9">
                            @Html.TextBoxFor(x => x.ServiceVM.CustomerName, new { @class = "form-control", name = "txtCustName" })
                            @Html.ValidationMessageFor(x => x.ServiceVM.CustomerName, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(x => x.ServiceVM.MachineCount, htmlAttributes: new { @class = "control-label col-3" })
                        <div class="col-9">
                            @Html.TextBoxFor(x => x.ServiceVM.MachineCount, new { @class = "form-control", name = "txtMcount" })
                            @Html.ValidationMessageFor(x => x.ServiceVM.MachineCount, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(x => x.ServiceVM.MachinePrice, htmlAttributes: new { @class = "control-label col-3" })
                        <div class="col-9">
                            @Html.TextBoxFor(x => x.ServiceVM.MachinePrice, new { @class = "form-control", name = "txtMprice" })
                            @Html.ValidationMessageFor(x => x.ServiceVM.MachinePrice, "", new { @class = "text-danger" })
                        </div>
                    </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                    <input type="submit" class="btn btn-primary" value="Save" />
                </div> 
            </div>
        </div>
    </div>
}

 

$('.openModal').on('click', function () {
    var quoteid = $(this).attr("data-quoteid");
    $.ajax({
        type: "GET",
        url: "/Service/GetServiceQuote/",
        contentType: "application/json; charset=utf-8",
        data: { "id": quoteid },
        datatype: "Json",
        success: function (data) {
            if (data != null) {
                jsonobj =
                    {
                        "quoteid": data.QuoteID,
                        "customerid": data.CustomerID,
                        "customername": data.CustomerName,
                        "listofsn2s": data.ListOfSN2s,
                        "machinecount": data.MachineCount,
                        "machineprice": data.MachinePrice,
                        "machineaddress": data.MachineAddress,
                        "machinecity": data.MachineCity
                    }
                PopulateModalJSON(jsonobj);
            }
        }
    });
});
function PopulateModalJSON(jsonObject) {
    var modalA = $('#modalInnerSQ');
    var body = $('.modal-body');
    var quoteid = modalA.find(body).find('#ServiceVM_QuoteID');
    var custid = modalA.find(body).find('#ServiceVM_CustomerID');
    var cust = modalA.find(body).find('#ServiceVM_CustomerName');
    var listsn2s = modalA.find(body).find('#ServiceVM_ListOfSN2s');
    var mcount = modalA.find(body).find('#ServiceVM_MachineCount');
    var mprice = modalA.find(body).find('#ServiceVM_MachinePrice');
    var maddress = modalA.find(body).find('#ServiceVM_MachineAddress');
    var mcity = modalA.find(body).find('#ServiceVM_MachineCity');
    if (jsonObject.expirationdate != null) {
        var datePartI = makeDateObject(jsonObject.expirationdate);
        var datePartII = dateToString(datePartI);
    }

    quoteid.val(jsonObject.quoteid);
    custid.val(jsonObject.customerid);
    cust.val(jsonObject.customername);
    listsn2s.val(jsonObject.listofsn2s);
    mcount.val(jsonObject.machinecount);
    mprice.val(jsonObject.machineprice);
    maddress.val(jsonObject.machineaddress);
    OpenServiceQuoteModal();
}
function OpenServiceQuoteModal() {
    $('#modalInnerSQ').modal('show');
}

I have tried with PrtialView but the result is same.

public JsonResult GetServiceQuote(int? id)
{
    if (id == null) { return null; }

    var vm = new ServiceReportViewModel();
    var model = context.Serv_Quotes.Where(x => x.QuoteID == id).FirstOrDefault();

    vm.QuoteID = model.QuoteID;
    vm.CustomerID = model.CustomerID.ToString();
    vm.CustomerName = model.CustomerName;
    vm.MachineCount = model.MachineCount;
    vm.MachinePrice = model.PricePerMachine;
    vm.MachineAddress = model.Address;
    vm.MachineCity = model.City;
    vm.MachineState = model.State;
    vm.MachineZipCode = model.ZipCode;
    return Json(vm, JsonRequestBehavior.AllowGet);
}

[HttpPost]
public ActionResult UpdateServiceTables(ServiceModel model)
{
    model.Customers = GetCustomersSQ();
    model.SerialNumbers = GetSerialNumbersSQ();
    model.City = GetCitiesSQ();
    model.State = GetStatesSQ();

    model.Settings = GetTableSettingsSQ();

    if (ModelState.IsValid)
    {
        var quote = context.Serv_Quotes.Where(x => x.QuoteID == model.ServiceVM.QuoteID).FirstOrDefault();
        quote.QuoteID = model.ServiceVM.QuoteID;
        quote.CustomerName = model.ServiceVM.CustomerName;
        quote.ListOfSN2s = model.ServiceVM.ListOfSN2s;
        quote.MachineCount = model.ServiceVM.MachineCount;
        quote.PricePerMachine = model.ServiceVM.MachinePrice;
        quote.Address = model.ServiceVM.MachineAddress;
        quote.City = model.ServiceVM.MachineCity;
        quote.State = model.ServiceVM.MachineState;
        ////UPDATE Quote Record
        context.Entry(quote).State = EntityState.Modified;
        context.SaveChanges();
        return RedirectToAction("SearchGet", model);
        //return RedirectToAction("Search", model);
    }
    else
    {
        //return View("VirtualService", model);
        //return RedirectToAction("GetServiceQuote", new { id = model.ServiceVM.QuoteID });
        return PartialView("ModalSQUpdate", model);
    }
    //return Json(model, JsonRequestBehavior.DenyGet);           
}

 

You are viewing reply posted by: dharmendr one year ago.
Posted one year ago

Hi bigbear,

Please follow these steps.

1. Create the class for properties with data annotation for validation purpose.

This class will be used to validate the user input in model popup.

public class CustomerModel
{
    [Required(ErrorMessage = "Name is required.")]
    public string Name { get; set; }
}

2. Add partial view and place the html with ValidationMessageFor to show inside the modal body.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<_Ajax_BeginForm.Models.CustomerModel>" %>
<%:Html.AntiForgeryToken() %>
<%:Html.ValidationSummary(true, "", new { @class = "text-danger" })%>
<table>
    <tr>
        <td>Name</td>
        <td>
            <%:Html.TextBoxFor(model => model.Name)%>
            <%:Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })%>
        </td>
    </tr>
</table>

3. Add code in controller for Ajax call and update.

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View(new CustomerModel());
    }

    [ValidateAntiForgeryToken]
    [HttpPost]
    [HandleError]
    public ActionResult UpdateServiceTables(CustomerModel model)
    {
        if (ModelState.IsValid)
        {
            ModelState.Clear();
            return PartialView("_SearchCustomer", model);
        }
        return PartialView("_SearchCustomer", model);
    }

    public JsonResult GetServiceQuote(int? id)
    {
        if (id == null) { return null; }
        var vm = new CustomerModel();
        vm.Name = "Test";
        return Json(vm, JsonRequestBehavior.AllowGet);
    }
}

4. Add View and modal popup html.

Privide id to modal-body and render the Partial View inside the modal-body.

Set modal-body id as UpdateTargetId for AjaxOptions.

<input type="button" class="openModal btn btn-danger" data-quoteid="1" value="Edit" />
<%using (Ajax.BeginForm("UpdateServiceTables", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "modalbody" }))
    {%>
<div class="modal fade" id="modalInnerSQ" tabindex="-1" role="dialog" aria-labelledby="lblSQmodal"
    aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    <b>Service Quote Details</b></h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="modalbody">
                <%:Html.Partial("_SearchCustomer")%>
            </div>
            <div class="modal-footer">
                <input type="submit" name="btnUpdate" value="Update" />
            </div>
        </div>
    </div>
</div>
<% } %>

5. Write javascript code to open the modal on button click.

<script type="text/javascript">
    $(function () {
        $('.openModal').on('click', function () {
            var quoteid = $(this).attr("data-quoteid");
            $.ajax({
                type: "GET",
                url: "/Home/GetServiceQuote/",
                contentType: "application/json; charset=utf-8",
                data: { "id": quoteid },
                datatype: "Json",
                success: function (data) {
                    var modalA = $('#modalInnerSQ');
                    var body = $('.modal-body');
                    var quoteid = modalA.find(body).find('#Name');
                    $(quoteid).val(data.Name);
                    OpenServiceQuoteModal();
                }
            });
        });
    });

    function OpenServiceQuoteModal() {
        $('#modalInnerSQ').modal('show');
    }
</script>

Then run and check.

Screenshot

Note: In this example i have hardcoded some values. You need to change as per your database values.