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,

Check this sample without using PartialView.

Model

public class CustomerModel
{
    public int? Id { get; set; }
    public Customer Customer { get; set; }
}

public class Customer
{
    [Required(ErrorMessage = "Name Required!")]
    public string Name { get; set; }
}

Controller

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

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

    [HttpPost]
    public ActionResult UpdateServiceTables(CustomerModel model)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("SearchGet", model);
        }
        return View("VirtualService", model);
    }
}

View

@model _Modal_Popup_Validation_MVC.Models.CustomerModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Index</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
    <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) {
                        if (data != null) {
                            var jsonobj = { "id": data.Id, "name": data.Customer.Name }
                            // Create function to populate Modal
                            PopulateModalJSON(jsonobj);
                        }
                    }
                });
            })
        });

        function PopulateModalJSON(jsonObject) {
            var modalA = $('#modalInnerSQ');
            var body = $('.modal-body');
            var id = modalA.find(body).find('#Id');
            var name = modalA.find(body).find('#Customer_Name');

            id.val(jsonObject.id);
            name.val(jsonObject.name);

            // Open the Modal (It's Populated)
            OpenServiceQuoteModal();
        }

        function OpenServiceQuoteModal() {
            $('#modalInnerSQ').modal('show');
        }
        function CloseServiceQuoteModal() {
            $('#modalInnerSQ').modal('hide');
        }
    </script>
</head>
<body>
    <div class="container">
        <input type="button" class="openModal btn btn-danger" data-quoteid="1" value="Edit" />
    </div>
    @using (Ajax.BeginForm("UpdateServiceTables", "Home", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "ajaxit" }))
    {                                                                                                       //modalInnerSQ
        @Html.AntiForgeryToken()
        <div class="modal" 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">×</span>
                        </button>
                    </div>
                    <div class="modal-body" id="ajaxit">
                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                        @Html.HiddenFor(x => x.Id)
                        <div class="form-group">
                            @Html.LabelFor(x => x.Customer.Name, htmlAttributes: new { @class = "control-label col-3" })
                            <div class="col-9">
                                @Html.TextBoxFor(x => x.Customer.Name, new { @class = "form-control", name = "txtCustName" })
                                @Html.ValidationMessageFor(x => x.Customer.Name, "", new { @class = "text-danger" })
                            </div>
                        </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>
    }
</body>
</html>