How to print data from database onto model popup box? - javascript

I have books retrieved from database in the Index view. Each one has a button below. When you click them a modal box should pop up with the corresponding book details (book img, name title, decsription, price etc) printed on it.
Index View:
<!-- language: lang-html -->
#model AuthorTest.Models.HomeModel
<!--razor codes where book properties are called-->
#foreach(var book in Model.Bestsales)
{
<a class="first__img" href="single-product.html"><img src="~/Uploads/img/#(book.Id + " .jpg ")"</a>
<h4>product.html">#book.Name</a></h4>
<ul class="prize d-flex">
<li>#book.Price</li>
</ul>
<!--modal-box pop-up button-->
<a data-toggle="modal" title="Quick View" data-id="#book.Id" class="modal-open" href="#productmodal"><i class="bi bi-search"></i></a>
}
I'm trying to pass a book id using ajax
<!-- language: lang-js-->
#section scripts{
<script>
$(".modal-open").click(function () {
var id = $(this).data("id");
$.ajax({
type: "POST",
url: "/Home/Details/" + id
});
});
</script>
}
into the "Details" action that retrieves related book and returns it to a view where modal box content is placed.
<!-- language: lang-cs-->
[HttpPost]
public ActionResult Details(int id)
{
HomeModel model = new HomeModel();
var book = db.Books.Where(b => b.Id == id).Include(b => b.Author).SingleOrDefault();
if (book == null)
{
HttpNotFound();
}
book.DisplayNumber++;
db.SaveChanges();
model.bookDetails = book;
return view( model);
}
This is the HomeModel class that I use to keep two models 1)list property of type Book to loop through my books in the Index view
2)property of Book type to call model-related book datas in "Details" view:
<!-- language: lang-cs-->
public class HomeModel
{
public List<Book> BestSales { get; set; }
public Book bookDetails { get; set; }
}
a view where modal box content is placed:
<-- language: lang-html-->
#model AuthorTest.Models.HomeModel
div id="quickview-wrapper">
<!-- Modal -->
<div class="modal fade" id="productmodal" tabindex="-1" role="dialog">
<div class="modal-dialog modal__container" role="document">
<div class="modal-content">
<div class="modal-header modal__header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="modal-product">
<!-- Start product images -->
<div class="product-images">
<div class="main-image images">
<img alt="big images" src="~/Uploads/img/#(Model.bookDetails.Id + ".jpg")">
</div>
</div>
<!-- end product images -->
<div class="product-info">
<h1>#Model.bookDetails.Name</h1>
<div class="rating__and__review">
</div>
<div class="price-box-3">
<div class="s-price-box">
<span class="new-price">#Model.bookDetails.Price</span>
<span class="old-price">$34.00</span>
</div>
</div>
<div class="quick-desc">
#Model.bookDetails.Description
</div>
<div class="addtocart-btn">
Add to cart
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
When I click modal-open button the id gets passed to the "Details" action, corresponding book is retrieved and takes me to the view. But it seems like modal box pops up before ajax runs action and therefore the data is not printed. Where do I make mistake? How to pass the book details into the modal-box correctly?

An Ajax call is asynchronous, so you must get in this mindset: when you work in a non sync way, you shall manage async calls with callbacks. jQuery offers different types of callback for the $.ajax() method, such as "success","error".... on and on. If the ajax call results in a server exception for instance, the HTTP result will be 500 and you can manage it in the "error" callback subscribing the callback with a your custom method that will be raised by jQuery. On the other way, the success callback must be subscribed by a method that accepts parameters where will be the server response (in this case, an html response). So, if the result is a success (HTTP Status code 200), you will have the HTML in that parameter, and you can use it to append in your modal (always with jQuery methods... or even in simple javascript if you like more)
Take a look to callbacks subscriptions:http://api.jquery.com/jquery.ajax/ in the "Callback Function Queues" section. You will find out that I gave you just a real basic explanation and there's a lot of more to learn!

Related

Django forms are not receiving form data using ajax call

I am writing a simple AJAX site using a Django back-end where you can create articles. Each article has an edit button, which can be used to modify that pre-existing article on the page. This button pops up an edit form (the issue at hand) in a Bootstrap Modal.
The edit form has only 3 fields: headline, subheading, and a date (for now). Whatever the field inputs are, they are not sent back to Django properly and the is_valid() method returns False every single time. This is what form.errors gives me as output every single time:
<ul class="errorlist"><li>headline<ul class="errorlist">
<li>This field is required.</li>
</ul>
</li>
<li>subheading<ul class="errorlist">
<li>This field is required.</li></ul></li>
<li>date<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
The "This field is required" is likely because the model does not have blank=True, so the form must be sending empty fields.
Below is all my code in question, including the form in HTML, the AJAX call, and the Django form.
views.py:
# Handles editing articles
class ArticleEdit(View):
def post(self, request, id):
editForm = ArticleForm(request.POST)
if editForm.is_valid():
print("Debug: Form is valid")
# No Logic here yet
return JsonResponse({'edited' : 'OK'}, status=200)
else:
print(editForm.errors)
return JsonResponse({'edited' : 'FAIL'}, status=200)
forms.py
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['headline', 'subheading', 'date']
widgets = {
'headline' : forms.TextInput(attrs={'class': 'form-control'}),
'subheading' : forms.TextInput(attrs={'class': 'form-control'}),
'date' : forms.TextInput(attrs={'class': 'form-control'}),
}
articles.html
<!-- Bootstrap Modal -->
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Article</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<!-- Edit Form -->
<form class="form-group" method="post" id="editArticleForm">
{% csrf_token %}
{{ editForm }}
<button type="button" class = "btn btn-outline-success my-3" id="finishEditButton">Finish</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
articles.js
function finishEdit()
{
editData = $('#editArticleForm').serialize();
console.log(editData);
$.ajax
({
url: '/' + currentlyEditing.data('id') + '/edited/',
data: {csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), data: editData, id: currentlyEditing.data('id')},
type: 'post',
success: function(data)
{
if (data.edited == "OK")
{
console.log("EDIT::RESPONSE OK");
}
else
{
console.log("EDIT::RESPONSE FAIL");
}
}
});
I've tried deleting the modal, and having the form as a simple element instead. I've also tried to rewrite my Ajax request but that hasn't worked either. Plus, the serialized data created from the form displays the information typed into the input fields, but it doesn't end up in Django.
In conclusion, my whatever my data is in my form in articles.html is not sent properly to Django, no matter what I type, and I cannot seem to figure out the problem. I would really appreciate some help with this.
Thank you all in advance.

Change a variable when a link is clicked

I have a page that loads the last 25 rows from a database and displays them in a table. I want to be able to click a link and have a modal popup that contains more information. I've got everything working except for knowing which row Id was clicked. Below is currently what I have. Model.ClickedId never changes from the default value so the popup has the same message everytime.
How can I make it so ClickedId on the backend is set to item.Id when the link is clicked?
Backend:
public int ClickedId { get; set; } = 0;
Front end:
#foreach (var item in Model.SFException)
{
<tr>
<td>
View <!-- Set ID to item.ID? -->
</td>
<td>
#Html.DisplayFor(modelItem => item.ObjectType)
</td>
<td>
#Html.DisplayFor(modelItem => item.ObjectKeyProperty)
</td>
<td>
#Html.DisplayFor(modelItem => item.ObjectKeyValue)
</td>
...
And the modal code where I am trying to display more information:
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Exception Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.DisplayFor(model => model.SFException[Model.ClickedId].StackTraceErrorMessage)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
There are a couple of ways I've done this in the past. Either:
Get all the information that all rows need and dump it on the page (maybe in hidden elements), then when the user interacts with your rows show/hide the relevant extra information. Depending on how much extra info you need there can be a bit of overhead with this.
Put the 'StackTraceErrorMessage' on the page somewhere like
<td class="open-modal" data-itemId="#item.Id">
View
<input type="hidden" value="#item.StackTraceErrorMessage" />
</td>
Then in JS look for when the 'View' text is clicked, move the StackTraceErrorMessage from the hidden area to the modal html and display the modal html
$(document).ready(function() {
$(".open-modal").click(function() {
// get the item id from the clicked on element
var itemId = $(this).data("itemId");
// get the relevant StackTraceErrorMessage and put in the modal html
var message = $(this).find('input').val();
$('.modal-body').html(message);
// show the modal html (presumably this has styles associated to make it look like a dialog)
$('.modal).show();
});
)};
The second options is, put the basic information on the page and then when the user interacts with it go back to the server-side to request more details and then display that. There's a bit more back-and-forth and setup for this method.
The link in your row would look something like this:
<td data-itemId="#item.Id" class="show-row-details">View</td>
Where the item id is stored as an attribute in the element and a class is attached so we can watch for clicks.
In your js you would then look for any clicks like :
$(document).ready(function() {
$(".show-row-details").click(function() {
// get the item id from the clicked on element
var itemId = $(this).data("itemId");
// make a request to the backend for more info
$.ajax({
url: baseUrl + "YourController/YourAction",
data: { itemId : itemId },
success: function (data) {
// put the data returned into the popup element on our page and make it visible
$('#popup').html(data);
$('#popup').show();
}
})
});
)};
So to support this on your page you would need an elment ready to recieve data from the backend
<div id="popup" style="display:none"></div>
and also you would need a controller and action on your backend that is going to return the Html that you want to display in the popup div (pretty much just an action that loads a partial view (i.e. no layout) with your 'modal code' in it).
Note: I haven't actually tried the above code, so there may be some syntax errors etc

MVC - Html.Action to retrieve element using Javascript, then pass it as parameter to Controller, then return a PartialView

View - My view has a modal that has an #Html.Action that calls the PartialViewResult in Controller. Notice the #Html.Action("RetrieveItemPrice", new { item_Id = 1 }) still has predefined item_Id.
Q#1: How do I create a function that will get an element's value and put it in the item_Id parameter before sending it to the Controller? Could this be inserted in the #Html.Action?
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="pvPrice" class="" style="border: 0px solid green; ">
#Html.Action("RetrieveItemPrice", new { item_Id = 1 })
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<table id="dbTable">
<thead>
<tr>
<th class="hidden">
#Html.DisplayNameFor(model => model.itemId)
</th>
<th>
#Html.DisplayNameFor(model => model.itemName)
</th>
</tr>
</thead>
<tbody id="dbBody">
#foreach (var item in Model.Items)
{
<tr>
<td class="hidden">
#Html.DisplayFor(modelItem => item.itemid)
</td>
<td>
#Html.DisplayFor(modelItem => item.itemname)
</td>
</tr>
}
</tbody>
</table>
Controller
public PartialViewResult RetrieveItemPrice(string item_Id)
{
var prices = from ip in _odb.ITEM_PRICE_MSTR
join i in _odb.ITEM_MSTR on i.ITM_ID equals i.ITM_ID
select new ItemModel
{
itemid = i.ITM_ID,
itemname = i.ITM_DESC,
itemprice = ip.ITM_PRICE,
defaultflag = ip.DEFAULT_FL,
startdate = DbFunctions.TruncateTime(ip.START_DT),
enddate = DbFunctions.TruncateTime(ip.END_DT),
createddt = i.CREA_DT
};
prices = prices.Where(i => i.itemid.ToLower().Contains(item_Id.ToLower()));
prices = prices.OrderByDescending(i => i.itemprice);
var vm = new ItemViewModel();
vm.Items = prices.ToPagedList(pageNumber, pageSize);
return PartialView("_ViewItemPrice", vm);
}
Q#2: When I return a PartialView in Controller using PartialViewResult, who's going to receive and display it in the View? I ran the code, but nothing is being displayed. I think I still lack codes in View to receive the returned PartialView in Controller
Assuming you have many items with different item_Id and you want to show the modal dialog when this item is clicked. You should be listen to the click event on the element, make an ajax call and get the response (partial view result) and use that to build your modal dialog content.
Assuming your main view has code like this
<table>
#foreach (var item in Model.Items)
{
<tr>
<td>#item.itemname</td>
<td><a href="#Url.Action("RetrieveItemPrice",new { item_Id = itemId})"
class="modal-link" >#item.itemname</a>
</td>
</tr>
}
</table>
<!-- The below code is for the modal dialog -->
<div id="modal-container" class="modal fade" tabindex="-1" role="dialog">
X
<div class="modal-content">
<div class="modal-body"></div>
</div>
This will generate links with css class modal-link for each item in the table. The href value of the links will be like YourControllerName/RetrieveItemPrice?item_id=123(123 will be replaced with actual itemid) Now listen to the click event on these, make an ajax call to the href attribute value of these links and use the response for populating the modal dialog content.
$(function () {
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$("#modal-container").remove();
$.get($(this).attr("href"), function (data) {
$('<div id="modal-container" class="modal fade">
<div class="modal-content" id="modalbody">'
+ data + '</div></div>').modal();
});
});
});
This code will replace the entire content of the modal with the partial view result coming from the RetrieveItemPrice action method. That means you need to include the necessary markup needed for the modal header and footer(with buttons) in the _ViewItemPrice partial view.
A#1: the code calling #Html.Action is executed on server-side, at that phase the html document has not been sent to client-side so you don't have to look for a way to retrieve element value. You can pass it directly to the call, instead, because the model used for rendering the view (including the element) should be accessible to the code in the modal.
If you place the modal markups right inside the view, you definitely can get #Model.ItemId, for example.
If you place the modal in a partial view, you can pass item id via ViewBag:
#Html.Partial("Modal", null, new ViewDataDictionary{{"ItemId", Model.ItemId}})
then use it in the modal markups:
#Html.Action("RetrieveItemPrice", new { item_Id = ViewBag.ItemId })
A#2: you should try if [ChildActionOnly] makes the action RetrieveItemPrice works.

ASP.net MVC 4 Validation Within bootstrap Modal and PartialView

In my application I was using simple View the Validation, both client and server side validation, was working fine, but now I have changed to bootstrap modal and PartialView. The problem is that Client Side Validation dosn't work any more and for server side validation when I click submit he redirect me to new page (see picture) instead of showing the error on the current modal pop-up.
Create Controller :
[HttpGet]
public ActionResult Create()
{
ViewBag.CAT_ID = new SelectList(db.CATEGORIE, "CAT_ID", "LIBELLE");
ViewBag.C_GARANT = new SelectList(db.GARANTIE, "C_GARANT", "LIB_ABREGE");
return PartialView("_Create");
}
//
// POST: /Taux/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(TAUX taux)
{
if (ModelState.IsValid)
{
db.TAUX.Add(taux);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CAT_ID = new SelectList(db.CATEGORIE, "CAT_ID", "LIBELLE", taux.CAT_ID);
ViewBag.C_GARANT = new SelectList(db.GARANTIE, "C_GARANT", "LIB_ABREGE", taux.C_GARANT);
return PartialView("_Create", taux);
}
_Create Partial View :
#model pfebs0.Models.TAUX
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="CreateTaux">Add</h3>
</div>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="modal-body">
<div class="form-group">
<div class="form-group">
<label for="Categorie">Categorie : </label>
#Html.DropDownList("CAT_ID", String.Empty)
#Html.ValidationMessageFor(model => model.CAT_ID)
</div>
//Other Form input.
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Submit</button>
</div>
}
</div>
<script>
$("select").addClass("form-control");
$("input").addClass("form-control");
$("label").addClass("control-label");
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval") }
Index View where I puted the modal :
<p>
#Html.ActionLink("Ajouter", "Create", "Taux",
new { id = "btnAdd", #class="btn btn-default"})
</p
<div id="modalDiv" class="modal fade" >
<div class="modal-dialog">
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$('#btnAdd').click(function () {
$('.modal-dialog').load(this.href, function () {
$('#modalDiv').modal({
backdrop: 'static',
keyboard: true
}, 'show');
});
return false;
});
});
</script> }
So what I have to add or change to Have client validation in my modal and for server validation to be redirected to modal, instead new page like in picture ?
You can rely on the built in bootstrap functionality of the role and data-target attributes. If you define your modal's role as "dialog" and give it an id then you can reference that in a HTML button with a data-target and data-toggle attributes.
You also need to avoid loading your _Create partial from an ajax request. Just load it along with Index using #Html.Partial. It will not appear in your view if the attributes are set correctly.
Here are the steps I did to get it working:
First modify your _Index to load partial view and update your modalDiv to define a role.
<div class="modal fade" id="modalDiv" tabindex="-1" role="dialog" aria-hidden="true">
#Html.Partial("~/{PathToView}/_Create.cshtml", new pfebs0.Models.TAUX())
</div>
Now instead of using #HtmlActionLink and JavaScript to load dialog, create a button as follows. Make sure to remove the JS click event code.
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#modalDiv">Ajouter</button>
Now bootstrap will handle showing and hiding dialog automatically with the defined role and data attributes and MVC validation will appear correctly. You can leave your controller code as-is.

Using Bootstrap Modal window as PartialView

I was looking to using the Twitter Bootstrap Modal windows as a partial view. However, I do not really think that it was designed to be used in this fashion; it seems like it was meant to be used in a fairly static fashion. Nevertheless, I think it'd be cool to be able to use it as a partial view.
So for example, let's say I have a list of Games. Upon clicking on a link for a given game, I'd like to request data from the server and then display information about that game in a modal window "over the top of" the present page.
I've done a little bit of research and found this post which is similar but not quite the same.
Has anyone tried this with success or failure? Anyone have something on jsFiddle or some source they'd be willing to share?
Thanks for your help.
Yes we have done this.
In your Index.cshtml you'll have something like..
<div id='gameModal' class='modal hide fade in' data-url='#Url.Action("GetGameListing")'>
<div id='gameContainer'>
</div>
</div>
<button id='showGame'>Show Game Listing</button>
Then in JS for the same page (inlined or in a separate file you'll have something like this..
$(document).ready(function() {
$('#showGame').click(function() {
var url = $('#gameModal').data('url');
$.get(url, function(data) {
$('#gameContainer').html(data);
$('#gameModal').modal('show');
});
});
});
With a method on your controller that looks like this..
[HttpGet]
public ActionResult GetGameListing()
{
var model = // do whatever you need to get your model
return PartialView(model);
}
You will of course need a view called GetGameListing.cshtml inside of your Views folder..
I do this with mustache.js and templates (you could use any JavaScript templating library).
In my view, I have something like this:
<script type="text/x-mustache-template" id="modalTemplate">
<%Html.RenderPartial("Modal");%>
</script>
...which lets me keep my templates in a partial view called Modal.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{{Name}}</h3>
</div>
<div class="modal-body">
<table class="table table-striped table-condensed">
<tbody>
<tr><td>ID</td><td>{{Id}}</td></tr>
<tr><td>Name</td><td>{{Name}}</td></tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
I create placeholders for each modal in my view:
<%foreach (var item in Model) {%>
<div data-id="<%=Html.Encode(item.Id)%>"
id="modelModal<%=Html.Encode(item.Id)%>"
class="modal hide fade">
</div>
<%}%>
...and make ajax calls with jQuery:
<script type="text/javascript">
var modalTemplate = $("#modalTemplate").html()
$(".modal[data-id]").each(function() {
var $this = $(this)
var id = $this.attr("data-id")
$this.on("show", function() {
if ($this.html()) return
$.ajax({
type: "POST",
url: "<%=Url.Action("SomeAction")%>",
data: { id: id },
success: function(data) {
$this.append(Mustache.to_html(modalTemplate, data))
}
})
})
})
</script>
Then, you just need a trigger somewhere:
<%foreach (var item in Model) {%>
<a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
<%=Html.Encode(item.DutModel.Name)%>
</a>
<%}%>
I have achieved this by using one nice example i have found here.
I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.
Complete and clear example project
http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals
It displays create, edit and delete entity operation modals with bootstrap and also includes code to handle result returned from those entity operations (c#, JSON, javascript)
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call #{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '#Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
Put the modal and javascript into the partial view. Then call the partial view in your page.
This will handle form submission too.
Partial View
<div id="confirmDialog" class="modal fade" data-backdrop="false">
<div class="modal-dialog" data-backdrop="false">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Missing Service Order</h4>
</div>
<div class="modal-body">
<p>You have not entered a Service Order. Do you want to continue?</p>
</div>
<div class="modal-footer">
<input id="btnSubmit" type="submit" class="btn btn-primary"
value="Submit" href="javascript:"
onClick="document.getElementById('Coordinate').submit()" />
<button type="button" class="btn btn-default" data-
dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
Javascript
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#Coordinate").on('submit',
function (e) {
if ($("#ServiceOrder").val() == '') {
e.preventDefault();
$('#confirmDialog').modal('show');
}
});
});
</script>
Then just call your partial inside the form of your page.
Create.cshtml
#using (Html.BeginForm("Edit","Home",FormMethod.Post, new {id ="Coordinate"}))
{
//Form Code
#Html.Partial("ConfirmDialog")
}

Categories

Resources