Callback to server using ajax - javascript

I am trying to do a callback to the server to return a partial view to my modal when i click the "Add Role" button, but nothing happens when I click the button.
JavaScript:
$(".addRole").on("click", function(){
bootbox.dialog({
title: "Create new role",
callback: function () {
$.ajax({
url: "/Uam/CreateRole/",
method: "POST",
success: function(){}
});
}
});
});
View:
#model List<Vidly.Models.AvailableRole>
#{
ViewBag.Title = "CreateRole";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Available Roles</h2>
<div id="addRoleForm">
<button class="btn btn-success pull-right addRole" type="button" data-toggle="modal">New Role</button>
</div>
Controller:
public ActionResult CreateRole(int? id){
if (id == null){
var menuViewModel = new RoleMenuViewModel{
Menus = GetMultiselectItems()
};
return View("SaveRole", menuViewModel);
}

Message attribute is mandatory for bootbox dialog
$(".addRole").on("click", function(){
bootbox.dialog({
message: '<p class="text-center">Please wait while Createing new role...</p>',
title: "Create new role",
callback: function () {
$.ajax({
url: "/Uam/CreateRole/",
method: "POST",
success: function(){}
});
}
});
});
http://bootboxjs.com/examples.html#bb-custom-dialog

I ended up using the basic bootstrap modal with a #html.RenderAction call in the modal body and a reference to the launch button. No JQuery used.
<button id="addRole-btn" class="btn btn-success pull-right btn-lg" data-toggle="modal" data-target="#modal-container">New Role</button>
<div id="modal-container" class="modal fade" role="dialog" width="500px">
<div id="role-container"></div>
<div class="modal-content">
<div class="modal-body">
#if (true)
{
Html.RenderAction("CreateRole", "Uam");
}
</div>
</div>

Related

Is there a possibility to bind the Form to a modal bootstrap window without using the load call?

I'm using ajax to make a request and open a modal bootstrap window afterwards. The problem is that when I use ajax, I make a request to my controller, and the return (modal content) I load as follows:
//modal loading
$('#contentModalFinanceiroParcela').html(data);
//exibição da modal
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
So far, everything perfect. The problem is that from then on, I can't bind the form to register the submit event of the form. In the function bindFormFinanceiroParcela, no matter how much I pass the "dialog", bind does not work.
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
Searching the forums, I found that the process works if I load the modal using the "load" command, as below, but I can't do it like that, otherwise it will make a second request to the controller, because previously, I already used ajax .
//That way it works, but I can't use it.
$('#contentModalFinanceiroParcela').load(url, function () {
$('#modalFinanceiroParcela').modal({
keyboard: true
}, 'show');
// Inscreve o evento submit
bindFormFinanceiroParcela(this);
stopLoadPage();
});
Is there a possibility that I can bind the form without using the "load" command mentioned in the script above?
function openModalFinanceiroParcelaSemURL(data) {
startLoadPage();
//Create the modal window block in the body of the page
if (!$("#modalFinanceiroParcela").data('bs.modal'))
CreateModalFinanceiroParcela();
//Load modal content via ajax request
$('#contentModalFinanceiroParcela').html(data);
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
stopLoadPage();
}
function bindFormFinanceiroParcela(dialog) {
$('form', dialog).submit(function (e, i) {
if ($(this).valid() || i) {
startLoadOneMoment();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
window.location = window.location;
} else {
$('#contentModalFinanceiroParcela').html(result);
bindFormFinanceiroParcela();
}
stopLoadOneMoment();
}
});
return false;
} else {
return false;
}
});
function CreateModalFinanceiroParcela() {
var html = '<div class="modal modal-primary modal-system" tabindex="-1" role="dialog" id="modalFinanceiroParcela" data-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="content-modal-system" id="contentModalFinanceiroParcela"></div></div></div></div>';
$("body").append(html);
}
RAZOR DELETE:
#using Retaguarda.Domain.Enuns
#model Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela.FinanceiroParcelaViewModel
#{
ViewData["Title"] = "Excluir Parcela";
Layout = null;
}
<div>
<form asp-action="Delete" id="frm-excluir-financeiro-parcela">
#Html.AntiForgeryToken()
<div class="modal-shadow">
<div class="modal-header modal-header-primary">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4><i class="modal-title text-center glyphicon glyphicon-trash"></i> #ViewData["Title"] </h4>
</div>
<div class="panel">
<div class="panel-body container-fluid pt-15 pl-15 pr-15">
<div class="form-horizontal">
<vc:summary />
<br />
<div class="message-delete">
#Html.HiddenFor(model => model.Id, new { id = "hid-financeiro-parcela-id" })
<i class="icon fa-trash" aria-hidden="true"></i>
<p>
Tem certeza de que deseja excluir a parcela #(Model.Parcela)?<br />
</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-md-offset-2 col-md-10">
<div class="float-right">
<div class="btn-group btn-group-sm mr-auto"
role="group">
<div class="btn-group btn-group-sm" role="group">
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
<button id="btn-excluir-financeiro-parcela" type="button" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>
<button id="btn-cancelar-financeiro-parcela" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Ajax call
$('#dtFinanceiroParcela').on('click', 'tr .btn-excluir-financeiro-parcela', function (e) {
e.preventDefault();
startLoadOneMoment();
var id = $(this).attr('data-id');
var data = { id: id };
var dataURL = jQuery.param(data);
$.ajax({
url: "/financeiro-parcela-gerenciar/remover-financeiro-parcela/" + id,
type: "GET",
// data: dataURL,
contentType: "application/json",
async: false,
success: function (result) {
if (typeof result.success !== 'undefined') {
if (!result.success) {
stopLoadOneMoment();
swal("Oops", result.message, "error");
return false;
}
}
// alert(this.url);
stopLoadOneMoment();
openModalFinanceiroParcelaSemURL(result);
return false;
},
error: function () {
stopLoadOneMoment();
alert("Oops! Algo deu errado.");
return false;
}
});
Your form inside razor does not contain any submit button because its commented out.
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
Remove the comment or change the type of the other button to "submit"
I guess the submit event is attached successfully but never called due to the missing submit button inside your form.

C# MVC JS not working/running on Partial view after ajax validation

I have a layout and in my layout I call my script code which is in my view.
#if (IsSectionDefined("VSscript"))
{
#RenderSection("VSscript");
}
I have a view and in my view I have the script section #section VSscript {
I also have an ajax section beginform that connects to a partialview
#using (Ajax.BeginForm("CreateServiceQuote", "Service", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "ajaxCreate", OnSuccess="quoteSuccess" }))
In the ajax portion I have my code for the partial
#Html.Partial("SQcreate")
All of the javascript im using is in VSscript and that is in my view.
In the partial view I have just the controls that I need.
When I first run the project everything works perfectly. After I run 1 set of validation the javascript no longer runs. My ajax onsuccess="" part always runs but the code needed in my document.ready does not run.
Here is my controller its just calling the partial view if its not valid.
public ActionResult SQcreate()
{
var model = new ServiceModel();
return PartialView(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateServiceQuote(ServiceModel model)
{
if (ModelState.IsValid)
{
context.Serv_Quotes.Add(serviceQuote);
context.SaveChanges();
ModelState.Clear();
return Json("QuoteSuccess", JsonRequestBehavior.AllowGet);
}
return PartialView("SQcreate", serviceModel);
}
Here is the layout
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Titler</title>
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/modernizr")
#if (IsSectionDefined("VSscript"))
{
#*#RenderSection("VSscript");*#
#RenderSection("VSscript", required: false)
}
</head>
<body style="padding-top: 0px;">
<div class="container-fluid">
#RenderBody()
</div>
<!-- Script Bundle 1 -->
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jQueryValScripts")
<!-- ORRR Script Bundle 2 MINIFIED -->
<!--Scripts.Render("~/bundles/jQueryValScripts")-->
<!--*Scripts.Render("~/bundles/jqueryui")*-->
<!--*Scripts.Render("~/bundles/bootstrap")-->
<!--*Scripts.Render("~/bundles/unobtrusive")*-->
#*#RenderSection("VSscript", required: false)*#
</body>
</html>
and the view
#model PartNumbers.Models.ServiceModel
#{
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
Layout = "~/Views/Shared/_LayoutPageI.cshtml";
ViewBag.Title = "Virtual Service";
//TempData["EmployeeID"] == null ? "" : TempData["EmployeeID"];
}
#section VSscript {
<script type="text/javascript">
$(function () {
$("#btnSQopenCon").on("click", function () {
$("#AddSQcontact").modal("show");
})
// jQuery UI Date Picker Class Object Name
$(".datepickerui").datepicker();
var modalQ = $('#AddQuote');
var custDDL = modalQ.find('.modal-body').find('#ServiceVM_CustomerName');
var sn2DDL = modalQ.find('.modal-body').find('#ServiceVM_SN2');
$(custDDL).change(function () {
//alert('testtesttest');
var cityName = $(custDDL).val();
var sn2Number = $(sn2DDL).val();
$.ajax({
url: '#Url.Action("SearchContactsList", "Service")',
data: { Customer: cityName, SN2: sn2Number },
datatype: "json",
success: function (data) {
//var dropdownlist = $('#ContactSearch');
var dropdownlist = modalQ.find('.modal-body').find('#ServiceVM_ContactName');
//$('#ServiceVM_ContactName');
dropdownlist.empty();
$.each(data, function () {
dropdownlist.append(
$('<option></option>').val(this.Value).html(this.Text)
);
});
}
});
});
})
function quoteSuccess(data) {
if (data == 'QuoteSuccess') {
$("#AddQuote").modal("hide");
window.location.reload();
//var quoteRefresh =
//$.ajax({
//})
}
function contactSuccess(data) {
if (data == "ContactSuccess") {
$("#AddSQcontact").modal("hide");
var modalQ = $('#AddQuote');
var custDDL = modalQ.find('.modal-body').find('#ServiceVM_CustomerName').val();
var sn2DDL = modalQ.find('.modal-body').find('#ServiceVM_SN2').val();
$.ajax({
url: '#Url.Action("SearchContactsList", "Service")',
data: { Customer: custDDL, SN2: sn2DDL },
datatype: 'json',
success: function (data) {
var dropdownlist = modalQ.find('.modal-body').find('#ServiceVM_ContactName');
dropdownlist.empty();
$.each(data, function () {
dropdownlist.append(
$('<option></option>').val(this.Value).html(this.Text)
);
});
}
});
</script>
}
<!-- CREATE Service Quote -->
#using (Ajax.BeginForm("CreateServiceQuote", "Service", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "ajaxCreate", OnSuccess="quoteSuccess" }))
{
<div class="modal" id="AddQuote" tabindex="-1" role="dialog" aria-labelledby="lblAjaxCreate" aria-hidden="true">
<div class="modal-dialog" role="document" style="width:750px;">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title text-center"><b>New Service Quote</b></h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="ajaxCreate">
#Html.Partial("SQcreate")
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success" value="Create Quote" />
</div>
</div>
</div>
</div>
}
<!-- CREATE CONTACT -->
#using (Ajax.BeginForm("CreateSQcontact", "Service", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "ajaxContact", OnSuccess = "contactSuccess" }))
{
<div class="modal" id="AddSQcontact" tabindex="-1" role="dialog" aria-labelledby="lblAjaxContact" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="text-center"><b>Create Contact</b></h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="ajaxContact">
#Html.Partial("SQcontact")
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success" value="Create Contact" />
</div>
</div>
</div>
</div>
}
My solution to this would be to watch the 'Network tab' in Dev tools. I found errors there about parts of my model not being loaded when switching and reloading views.

How to call a partial view within a Modal using Jquery

I have a list of products and you want to display a modal window to edit the parameters of these products
for this you have in each row a button that calls the modal ....
my Edit button in Index.cshtml:
<td>
Editar
</td>
my script in Index.cshtml:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$("#EditModalBody").load(url, function () {
$("#myModalEditar").modal("show");
})
}
</script>
my modal Bootstrap in Index view:
<div class="modal fade" id="myModalEditar">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Editar Producto</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="EditModalBody">
</div>
</div>
</div>
</div>
my ActionResult in controller:
public ActionResult EditarProducto (int Kn_CodigoProducto)
{
Producto model = new Producto();
if(Kn_CodigoProducto >= 0)
{
var producto = db.Productoes.Where(c => c.Kn_CodigoProducto == Kn_CodigoProducto).FirstOrDefault();
model.v_Nombre = producto.v_Nombre;
}
return PartialView("_PartialEditar", model);
}
and my partial view that receives the model sent from the controller:
#model Dominio.Producto
<div class="jumbotron">
<label>Esto es una prueba #Model.v_Nombre</label>
</div>
I have the partial view inside the folder along with the Index.cshtml view
Also I have referenced the corresponding scripts, what is happening? What is missing? It is the first time that I work with partial and modal views ... am I doing it correctly?
Expected behavior: when you click on the edit button, the modal opens
Behavior obtained: although when clicking on the edit button it enters the action of my controller, it does not show the modal
any help for me?
Instead of this:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$("#EditModalBody").load(url, function () {
$("#myModalEditar").modal("show");
})
}
</script>
Can you try this:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$.ajax({
url: url,
type: 'GET',
success: function (result) {
$('#EditModalBody').html(result);
$("#myModalEditar").modal("show");
},
error: function (xhr, status) {
alert(status);
}
});
}
</script>
You don't need to write jquery to invoke modal popup, instead you can use data-toggle and data-target attribuites.
Editar

MVC Bootstrap Partial View ValidationMessageFor execute on loading Page

Im am doing an MVC, Bootstrap App.
I open a Bootstrap Partial View from Jquery passing Model as Parameter.
From Controller I return Partial View and I open it from Jquery.
The Problem I found, is that ValidationMessageFor is executed when Partial View is loaded... I can not find why.
The process is like this... I have an Image that called a JavaScript function...
img id="btnEmail" src="~/Content/Images/Email.png" onclick="btnEmail('param1',Param2)"
Here is My Jquery
function btnEmail(nick, user_id) {
--validate if user is logged and call function that call Partial View
if (SearchLogin())
SendMail();
}
function SendMail() {
user_id = $('#CommentUser_id').val();
nick = $('#LblCommentName').val();
if (user_id == $('#User_id').val())
return;
var model = { Object_id: $("#Upload_id").val(), Nick: nick, UserDestination_id: $("#User_id").val(), Parent_id: null, UserOrigin_id: user_id};
$.ajax(
{
type: "POST",
url: '#Url.Action("Email", "Contact")',
data: model,
success: function (result) {
$("#myModalContact").html(result).modal({ backdrop: "static" });
},
});
"static" });
}
Here is my
Controller Method
public async Task<ActionResult> Email(ContactModel model)
{
return PartialView("_Contact", model);
}
And Here is my Partial View
If I called my Partial View like this
<div class="modal fade" id="myModalContact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
#Html.Partial("~/Views/Contact/_Contact.cshtml", new TableAvivaVoz.Models.ContactModel() { Object_id = Model.upload.Upload_id, Nick = Model.upload.Nick, UserDestination_id = Model.upload.User_id, Parent_id = null,UserOrigin_id=Model.User_id });
</div>
it Works fine...
here is part of My Partial View
#model TableAvivaVoz.Models.ContactModel
#{
AjaxOptions ajaxOpts = new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "sucessContact",
};
}
#using (Ajax.BeginForm("XXX", "Contact", ajaxOpts))
{
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">
</h4>
</div>
<div class="myPartialContact">
<div class="alert alert-success hidden">
</div>
</div>
#Html.AntiForgeryToken()
<div style="padding-bottom:220px">
<div class="modal-body">
<div class="col-md-10">
#Html.TextAreaFor(model => model.Description, 10, 80, new { #class = "txtDescQ", placeholder = "Ingresa un mensaje", #rows = 8, onclick = "OcultarRecomend();" })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="myPartialContactBtn modal-footer">
<button type="button" class="btn btn-default visible btnOk" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary visible btnOk" id="btnSave">Enviar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
}
Any ideas what is wrong?
You get errors on load because you are passing a erroneous Model to the action Email(ContactModel model).
When you ajax post, the Model binder validates the model and adds errors to the model state.
To fix this do as below:
public async Task<ActionResult> Email(ContactModel model)
{
ModelState.Clear();
return PartialView("_Contact", model);
}
Let me know if it helps.

Insert Data from Modal Bootstrap MVC 4 + JQuery (Post Method)

I have a modal form that save me on certain data information, work correctly, but I need to update a in my view with the response and doesn't work correctly and bring me a list without format and class css, like when an error occurs, the modal disappears and brings back a page without css with all the validates error, what I have wrong in my code or that I do to fix it?
My Partial View
#model ControlSystemData.Models.Tourist
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel-Update">Ingresar Turista</h4>
</div>
#using(#Html.BeginForm("Create","Tourist", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<div class="modal-body" style="text-align:center; padding:10px;">
#if (!string.IsNullOrWhiteSpace(ViewBag.Error))
{
<div class="alert alert-danger alert-dismissable" id="danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#ViewBag.Error
</div>
}
<div class="panel-body">
<div class="form-group">
#Html.TextBoxFor(u => u.Name, new { #class = "form-control", #placeholder = "Nombre del Pasajero" })
#Html.ValidationMessageFor(u => u.Name)
</div>
#*More Data Here*#
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</fieldset>
}
My Modal Bootstrap
<!--Modal Tourist-->
<div class="modal fade" id="Modal-Tourist" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<p class="body">
</p>
</div>
</div>
</div>
<!--End Modal Tourist-->
My Controller
[HttpPost]
public ActionResult Create(Tourist collection)
{
if (ModelState.IsValid)
{
db.Tourist.Add(collection);
db.SaveChanges();
return RedirectToAction("IndexByEventsTourist", "Tourist", new { id = collection.id });
}
Response.StatusCode = 400;
return PartialView("Create", collection);
}
My Script
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
function clearErrors() {
$('#msgErrorNewTourist').html('');
$('#alert').html('');
}
function writeError(control, msg) {
var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
$('#' + control).html(err_msg);
}
$(document).ready(function () {
$('#Modal-Tourist form').on('submit', function () {
if ($(this).valid()) {
$.ajax({
url: '#Url.Action("Create","Tourist")',
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
$("#eventsDetailsList").html(result);
},
error: function (err) {
writeError('body', 'Wrong Data');
}
});
}
return false;
});
function getRequest(url) {
jQuery.noConflict();
$.ajax({
url: url,
context: document.body,
success: function (data) {
$('.modal-content p.body').html(data);
$('#Modal-Tourist').modal('show');
$('#Name').focus();
},
error: function (err) {
writeError('msgErrorNewTourist', err.responseText);
}
});
}
$('a.newTourist').click(function () {
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
});
</script>
I need that the modal stay in your position with your errors or rendering my correctly with the update.
Thanks
Images
RedirectToAction
public ActionResult IndexByEventsTourist(int id)
{
ViewBag.id = id;
var eventsById = db.Events.Where(u => u.id == id).FirstOrDefault();
ViewBag.Events = eventsById;
var touristByEvent = db.Tourist.Where(u => u.id == id).Include(u => u.Events).ToList();
ViewBag.TouristByEvent = touristByEvent;
return PartialView("IndexByEvents", touristByEvent);
}
Parent page (Render Div with the Partial Render or Update from Modal)
<div class="col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-plus"></i> Add
</div>
<div class="panel-body">
<div class="row">
<div id="msgErrorNewTourist"></div>
<div class="col-lg-12" id="eventsDetailsList">
#{Html.RenderAction("IndexByEventsTourist", "Tourist", new { id = Model.id });}
</div>
</div>
</div>
</div>
</div>
</div>
After many tries, I changed the <script></script> (my script it was very obsolete) and I modified the <script> of this answer for my intent of load content dynamically and Validate the form before Post, Many Thanks to Sthepen Muecke for provide me a solution and clarify my issues... Thank you so much.
New Code Script for Load Content Dinamically and Validate Inputs in Modal Bootstrap 3
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('a.newTourist').click(function () {
var url = '#Url.Action("Create", "Tourist", new { id = #Model.id })';
$(jQuery.noConflict);
$('#ModalContent').load(url, function (html) {
var form = $("#Modal-Tourist form");
$.validator.unobtrusive.parse(form);
$("#Modal-Tourist").modal('show');
form.submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
var content = '#Url.Action("IndexByEventsTourist", "Tourist", new { id = #Model.id })';
$('#eventsDetailsList').load(content);
}
});
return false;
});
});
});
});
</script>

Categories