Django Angularjs How to call Http request with specific Id - javascript

i am very new in angularjs.I am trying to pull data in one of my django template using angularjs.This is the view by which i actually trying to pull data.
def download_history(request,download_id):
from django.core import serializers
download_history = DownloadHistory.objects.filter(user = request.user,pk=download_id)
ctx_detail_history = serializers.serialize('json', download_history)
return HttpResponse(ctx_detail_history)
this is the urls
url(r'^history_detail/(?P<download_id>\d+)/$',views.download_history,name = 'download_history'),
and this is my template where i am trying to pull data and trying to show in a jquery pop up modal.
{% extends 'base.html' %}
{% block title%}User Subscription {%endblock%}
{%block content%}
<div style="margin-top:100px;background-color:#85ADFF;" ng-app='history'>
<table class="table table-striped" >
{%for download_history_name in download_history%}
<tr>
<td><button type='button' data-toggle="modal" data-target="#myModal"><a href={%url 'download_history' download_history_name.id %} >{{download_history_name.name}} and the id {{download_history_name.id}}</a></button></td>
</tr>
{%endfor%}
</table>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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="myModalLabel">Objact Name</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-striped" ng-controller='HistoryCtrl'>
<tbody>
<tr>
{[{detail_history.fields.name}]}
{[{detail_history.fields.download_rate}]}
{[{detail_history.fields.photo.url}]}
{[{detail_history.fields.downloaded_time}]}
{[{detail_history.fields.DuePayment}]}
</tr>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
{%block extrajs%}
<script>
var app = angular.module('history',[]);
app.config(function($httpProvider){
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
app.config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
});
app.controller('HistoryCtrl',['$scope','$http' , function($scope,$http){
$http.get('/history/history_detail/(? P<download_id>\d+)/').success(function(data){
//$scope.doToggle=false;
$scope.detail_history=data;
}).error(function(data,status){
$scope.data = data || 'Request Fails';
$scope.status = status;
console.log(data)
});
}]);
</script>
{%endblock%}
{%endblock%}
now the problem is ,though i am trying to pull data with a specific id,but its not working,, in fact if i inspect the page ,it shows the return URL something that
http://localhost:8000/history/history_detail/(?Pd+)/
now whats the problem,definitely i make a mistake here,but i am very new in angularjs and can not figure it out.Is it possible to solve the problem using ng-click function?

From a cursory examination of your JavaScript it appears that you're trying to make a GET request to a URL including a regular expression. This makes sense for your Django configuration because you're telling the application to expect a number in the url that you assign to a variable named download_id. It appears you have copied this URL directly into your JavaScript where in fact you should be providing a specific download id in your GET request (e.g. '/history/history_detail/12345/').

Related

Update asp-route-id with jQuery

I'm building a razor pages application, and I want to use a modal as a partial view.
Foreach loop from where I'm opening the modal:
#foreach (var item in Model.SourceFiles)
{
<tr>
<td>#item.Id</td>
<td>#item.FileName</td>
<td>#item.Created</td>
<td>
#(item.IsConverted == true ? "Exported" : "Imported")
</td>
<td>
<button type="submit" class="btn btn-primary" asp-page-handler="FileContent" asp-route-fileId="#item.Id">View</button>
</td>
<td>
#if ((await authorizationService.AuthorizeAsync(User, "DeletePolicy")).Succeeded)
{
Delete
}
</td>
</tr>
}
I'm trying to set a new value of an asp-route-id tag using javaScript (jQuery), but I cant get it to work.
function triggerDeleteModal(itemId) {
$('#' + 'deleteModal').modal('toggle');
$("#confirmDeleteButton").attr('asp-route-deleteid', itemId)
}
Modal (partial view):
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalTitle" 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="deleteModalTitle">Caution!</h5>
</div>
<div class="modal-body">
<p style="white-space: pre-wrap;">#Model.DeleteModalText</p>
<p></p>
</div>
<div class="modal-footer">
<button type="submit" id="confirmDeleteButton" class="btn btn-secondary" data-bs-dismiss="modal">Yes</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
When pressing the yes-button (#confirmDeleteButton) in the modal to submit the form, the id is not getting passed in the asp-route-deleteid tag helper, and the id is always 0 in the OnPost-method.
Code behind where deleteid always is 0:
public async Task<IActionResult> OnPostAsync(int deleteid)
{
//code for deleting stuff
}
When trying to console.log the value of any attribute besides asp-route tags, the value is shown. When trying to log the value of an asp-route tag, the value is undefined.
Any ideas of how I can get the asp-route-deleteid to be passed to the code behind?
BR
The asp-route-* attribute works on tag helpers, which are server-side components. It is not rendered to the browser and is inaccessible to JavaScript. It is designed to work with elements that have an href, action or formaction attribute, and it either adds the attribute value to the query string of the generated href, or as a URL segment depending on the route template for the target page.
Generally, you shouldn't pass POST data within the URL, so instead, you can wire up a click event handler to the confirmDeleteButton that initiates an AJAX post that passes the deleteid:
$('#confirmDeleteButton').on('click, function(){
$.post('/yourpage',{deleteid: itemId}, function(){
// process the call back
})
})

Converting Bootstrap 3 remote modal to Bootstrap 4 modal with parameters

So in the near future my shop is going to upgrade to Bootstrap 4 but we cannot do this until we solve the issue with using remote modals. Here is an example of how we load our modals. The reason we use remote modals is because the modal-body is dynamic and may use different file based on the url. I have heard that using jQuery("#newsModal").on("load",..) is an alternative but how could I do this? I found this but I am not sure how my anchor would look and how to build the url to load the remote data.
Global PHP include file:
<div id="NewsModal" class="modal fade" tabindex="-1" role="dialog" data-
ajaxload="true" aria-labelledby="newsLabel" 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>
<h3 class="newsLabel"></h3>
</div>
<div class="noscroll-modal-body">
<div class="loading">
<span class="caption">Loading...</span>
<img src="/images/loading.gif" alt="loading">
</div>
</div>
<div class="modal-footer caption">
<button class="btn btn-right default modal-close" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
modal_news.php file:
<form id="newsForm">
<div id="hth_err_msg" class="alert alert-danger display-hide col-lg-12 col-md-12 col-sm-12 col-xs-12">
You have some errors. Please check below.
</div>
<div id="hth_ok_msg" class="alert alert-success display-hide col-lg-12 col-md-12 col-sm-12 col-xs-12">
✔ Ready
</div>
<!-- details //-->
</form>
Here is how we trigger the modals :
<a href="#newsModal" id="modal_sbmt" data-toggle="modal" data-target="#newsModal"
onclick="remote='modal_news.php?USER=yardpenalty&PKEY=54&FUNCTION=*GENERAL'; remote_target='#NewsModal .noscroll-modal-body'">
<span class="label label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
Promotional Ordering
</a>
I think I need to do something like this when building anchor dynamically:
a) Replace paramters with data-attrs
b) Use the event invoker to get the data-attrs using event.target.id
Thanks to Tieson T. and this post I was able to effectively pass parameters to the remote modal using this technique except if you have multiple modals
I have also included some helpful techniques inside this example as to how you may pass parameters to the remote modal.
bootstrap_modal4.php:
<div class="portlet-body">
Add Attendee <i class="fa fa-plus"></i>
</div>
<!-- BEGIN Food Show Attendee Add/Edit/Delete Modal -->
<div id="attendee" class="modal fade" tabindex="-1" role="dialog" data-ajaxload="true" aria-labelledby="atnLabel" aria-hidden="true">
<form id="signupForm" method="post">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<label id="atnLabel" class="h3"></label><br>
<label id="evtLabel" class="h6"></label>
</div>
<div class="modal-body">
<div class="loading"><span class="caption">Loading...</span><img src="/images/loading.gif" alt="loading"></div>
</div>
<div class="modal-footer">
<span class="caption">
<button type="button" id="add_btn" class="btn btn-success add-attendee hidden">Add Attendee <i class="fa fa-plus"></i></button>
<button type="button" id="edit_btn" class="btn btn-info edit-attendee hidden">Update Attendee <i class="fa fa-save"></i></button>
<button type="button" id="del_btn" class="btn btn-danger edit-attendee hidden">Delete Attendee <i class="fa fa-minus"></i></button>
<button class="btn default modal-close" data-dismiss="modal" aria-hidden="true">Cancel</button>
</span>
</div>
</div>
</div>
</form>
</div>
<script>
jQuery(document).ready(function() {
EventHandlers();
});
function EventHandlers(){
$('#attendee').on('show.bs.modal', function (e) {
e.stopImmediatePropagation();
if($(this).attr('id') === "attendee"){
// Determines modal's data display based on its data-attr
var $invoker = $(e.relatedTarget);
var fscode = $invoker.attr('data-fscode');
console.log(fscode);
// Add Attendee
if($invoker.attr('data-atnid') === "add"){
$("#atnLabel").text("Add New Attendee");
$(".add-attendee").removeClass("hidden");
}
else{ //edit/delete attendee
$("#atnLabel").text("Attendee Maintenance");
$(".edit-attendee").removeClass("hidden");
}
//insert hidden inputs
//add input values for post
var hiddenInput = '<INPUT TYPE=HIDDEN NAME=FSCODE VALUE="' + fscode + '"/>';
$("#signupForm").append(hiddenInput);
}
});
$('#attendee').on('hidden.bs.modal', function (e) {
$(".edit-attendee").addClass("hidden");
$(".add-attendee").addClass("hidden");
$("#signupForm input[type='hidden']").remove();
});
// BOOTSTRAP 4 REMOTE MODAL ALTERNATIVE FOR BOOTSTRAP 3v-
$('#add-attendee').on('click', function(e){
$($(this).data("target")+' .modal-body').load($(this).data("remote"));
$("#attendee").modal('show');
});
}
</script>
bootstrap_remote_modal4.php:
<form id="signupForm">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
Hello World!
</div>
</form>
<script>
$(document).ready(function(){
console.log('<?php echo $_GET["USERNAME"]?>'); //passed through url
});
</script>
NOTE: I am having problems with event propagation during the show.bs.modal event which I have a global show.bs.modal that is propagating up to this event handler due to multiple modals so if you have multiple modals make sure to handle them correctly.
Here is a screen shot of the results which clearly show propagation is taking place but the parameter passing techniques are working.
You might find it easier to use something like Bootbox.js, which can be used to dynamically create Bootstrap modals.
Given what you've shown, it would work something like:
trigger modal
with
$(function(){
$('.show-modal').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.get(url)
.done(function(response, status, jqxhr) {
bootbox.dialog({
title: 'Your Title Here',
message: response
});
});
});
});
This assumes response is an HTML fragment.
Bootbox hasn't officially been confirmed to work with Bootstrap 4, but I haven't run into any problems with it yet (modals seem to be one of the few components that don't have updated markup in BS4).
Disclaimer: I am currently a contributor to Bootbox (mainly updating the documentation and triaging issues).
If you must use only the Bootstrap modal, you're actually after load(). You would probably do something like:
$(function(){
$('.show-modal').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
var dialog = $('#NewsModal').clone();
dialog.load(url, function(){
dialog.modal('show');
});
});
});

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.

Method Not Allowed when using url for in jquery

How to pass parameters inside an URL for in javascript?
I have a case like this:
$('.btn-delete').click(function () {
var user_id = $(this).attr('userid');
console.log(user_id);
$('#modal-form').attr('action', "{{ url_for('admin.delete_user' , id="' + user_id +'" ) }}");
});
user_id variable has a value 56f52ea551d72027711157d6
If I do like this I get Method Not Allowed because the URL looks like this:
/admin/users/delete/%27%20+%20user_id%20+%27
How should I pass arguments in this part?
$('#modal-form').attr('action', "{{ url_for('admin.delete_user' , id="' + user_id +'" ) }}");
please somebody help me?
Edit:
The method that I use in route admin.delete_user in python is:
mod_admin.add_url_rule( '/users/delete/<string:id>', methods=['GET'])
def delete_user(self, id):
mongo.db.users.remove({'_id': ObjectId(id)})
return redirect(url_for('admin.users'))
And the modal popup:
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span></h4>
</div>
<form id="modal-form" action=" " method="POST">
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm btn-style" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default btn-sm btn-filter-apply btn-style" >Yes</button>
</div>
</form>
</div>
</div>
Because the template {{ }} is evaluated by jinja and converted to a string before the browser ever sees it, you don't need to concatenate all of the strings like you have shown. The id parameter should be passed as a standard keyword arguments.
$('#modal-form').attr('action', "{{ url_for('admin.delete_user' , id=user_id|string) }}");
You will also need to allow POST requests to the specified URL by updating this
mod_admin.add_url_rule( '/users/delete/<string:id>', methods=['GET', 'POST'])
UPDATE
Because user_id is actually defined in javascript, this is an issue because user_id is not accessible to jinja. To get around this, you will need to create your URL in this way:
$('#modal-form').attr('action', "{{ url_for('admin.delete_user') }}" + user_id);

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