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.
Related
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.
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
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>
I have an Index View and when I click the Edit button, I post to the Edit View (via the Controller) and display a bootstrap modal popup.
By posting to the Edit View, the Controller/View automatically handle getting and displaying the correct data on the modal popup.
Once I'm on my Edit View with the dialog box appearing and I click on the Close button, I simply want to link back to the Index page again; but instead, am getting an error with the path of the url. The new path I want to link to is being "tacked on" to the original path instead of replacing it.
I'm using the Url.Action method inside the click event of the Close button (of which I verified it's hitting) and have verified the location.href url is exactly what is in the url variable as you see in the code.
What do I need to do to correctly link back to the Index url?
Index View
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>Edit
Edit Controller
// GET: Categories/Edit/5
public async Task<ActionResult> Edit(short id)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = await db.GetCategoryIDAsync(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
Edit View
#model YeagerTechDB.Models.Category
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="modal" id="categoryEditModal" tabindex="-1" role="dialog" aria-labelledby="categoryModal-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="categoryModal-label">Category Description</h4>
</div>
<div class="modal-body">
<div class="form-group">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CategoryDescription, new { #class = "control-label required col-offset-1 col-lg-3 col-md-3 col-sm-3 col-xs-3" })
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
#Html.EditorFor(model => model.CategoryDescription, new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.CategoryDescription, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="btnCloseCategory">Close</button>
<button type="submit" class="btn btn-primary" id="btnSaveCategory">Save</button>
</div>
</div>
</div>
</div>
<div>
#Html.Hidden("categoryEditUrl", Url.Action("Edit", "Category", new { area = "Categories" }))
#Html.Hidden("catID", Model.CategoryID)
</div>
#section Scripts {
<script>
$(document).ready(function ()
{
if (typeof contentEditCategory == "function")
contentEditCategory()
});
</script>
}
JS for Edit View
$('#btnCloseCategory').click(function (e)
{
var url = '#Url.Action("Index", "Category", new { area = "Categories" })';
location.href = url;
return false;
});
Image of modal popup
Image of error
Assuming your javascript is in an external file you could do the following:
Attach the url to your button within your view with a data attribute as follows:
<button type="submit" class="btn btn-default" id="btnCloseCategory"
data-url="#Url.Action("Index", "Category", new { area = "Categories" })">Close</button>
Then pull back the url with the data method as follows:
$('#btnCloseCategory').click(function (e)
{
var url = $(this).data('url');
location.href = url;
return false;
});
Try changing type="submit" to type="button" for your Close button.
<button type="button" class="btn btn-default" id="btnCloseCategory">Close</button>
I have an MVC 4 application containing a grid with a link button to trigger the display of record details. I'm using a bootstrap modal dialog to display record details when the user selects a grid row.
I don't want to load the record details unless they are asked for; there are too many data elements involved (1000+).
The grid page uses a modal div containing the partial page (with a ViewModel reference).
I need the partial page's ViewModel to refresh prior to the display of the dialog. so when the user clicks the link, I get the record id from the grid and use it to create the url to the controller method - which seems to work, but seems to happen AFTER the dialog is shown.
How do I get this to work?
This code is in my Index.cshtml:
×
Account Number: #Html.DisplayFor(model => model.AccountNumber)
#{Html.RenderPartial("_KeyTable");}
#{Html.RenderPartial("_LoanTable");}
Close
$(document).ready(function () {
$("#divDialog").hide();
$("#btnClose").hide();
$("#lblAcceptAll").show();
$("#OnHoldsGrid").focus();
pageGrids.OnHoldsGrid.onRowSelect(function (e) {
accountNumber = e.row.AccountNumber;
});
$(".modal-link").click(function (event) {
event.preventDefault();
$('#detailsModal').removeData("modal");
var url = '#(Url.Action("_DetailsForModal", "Home", null, Request.Url.Scheme))?accountNumber=' + accountNumber;
$('#detailsModal').load(url);
$('#detailsModal').modal('show');
//alert(url);
});
});
// This code is in my Controller:
public ActionResult _DetailsForModal(string accountNumber)
{ // This refreshes the data in the ViewModel:
LOIHoldsViewModel model = new LOIHoldsViewModel();
model.GetLOIHoldExtended(accountNumber);
return PartialView("_DetailsForModal", model);
}
// This code is in my partial page _KeyTable.cshtml:
#model LOIHolds.Models.LOIHoldsViewModel
<div id="divKeyTable">
<br />
<hr />
<div class="KeyTableExpandContent">
<h2>Show/Hide Key Table Information</h2>
</div>
<label>Provider Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.ProviderDate)
<label>PFI Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.PFIDate)
<label>User Accept Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.UserAcceptDate)
<label>User Deny Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.UserDenyDate)
<label>Process Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.ProcessDate)
<label>Fiserv Accept Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.FiservAcceptDate)
</div>
<script>
$('.KeyTableExpandContent').click(function () {
$('.divKeyTable').toggle();
});
</script>
// This is the partial _DetailsForModal.cshtml:
#model LOIHolds.Models.LOIHoldsViewModel
<div class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="detailsModalLabel"><label>Account Number: </label>#Html.DisplayFor(model => model.AccountNumber) </h4>
</div>
<div class="modal-body">
<p>
#{Html.RenderPartial("_KeyTable");}
#{Html.RenderPartial("_LoanTable");}
</p>
</div>
<div class="modal-footer">
<button type="button" id="CancelModal" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
You will have to use Ajax when you click the .modal-link:
$(".modal-link").click(function (event) {
var mUrl = '#(Url.Action("DetailsForModal", "Home", null, Request.Url.Scheme))?accountNumber=' + accountNumber;
$.ajax({
url: mUrl,
success:function(result){
// result should contain PartialView from Controller
//Assign Modal DIV the PartialView
$('#detailsModal').html(result);
$('#detailsModal').modal('show');
}
});
}
Put your Modal Logic in a Partial View, then Create a function in Home Controller: Something like this:
public ActionResult DetailsForModal(int accountNumber){
var model = new PartialModalDialogViewModel();
// Load Modal Data
return PartialView("PartialViewName", model);
}
EDIT:
Try removing this from the Modal Partial View and put in somewhere in the _Layout.cshtml
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel" aria-hidden="true">
</div>