asp.net mvc bootstrap tab add javascript including partialview automatically - javascript

First of all i want to add purchase and sales in same view.And there will be many to one sales or many to one purchases. So i need to call sales model several times in one view with partial view. Then i encountered such a problem.
I have problem with MVC bootstrap tabs. I have one bootstrap tab. In first tab call partialview static like
#Html.Partial("_PurchaseDeal")
But then i add new tabs with add tab button. It is normally adds tabs and load partialview with this code.
<script type="text/javascript">
$(".purchase").on("click", "a", function (e) {
e.preventDefault();
if (!$(this).hasClass('add-purchase')) { debugger
$(this).tab('show');
}
})
.on("click", "span", function () {
$(this).parent().remove();
$(".purchase li").children('a').first().click();
});
$('.add-purchase').click(function (e) {
e.preventDefault();
var id = $(".purchase").children().length; //think about it ;)
var tabId = 'purchase_' + id;
debugger
$(this).closest('li').before('<li>P-'+id+' <span> x </span></li>');
$('.purchasetab').append('<div class="tab-pane" id="' + tabId + '">' + '</div>');
debugger
$.ajax({
url: '#Url.Action("ReturnPurchasePartial", "DEALs")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'html',
success: function (data) {
debugger
$('#'+tabId).html(data);
},
error:function()
{
alert('Could not save the deal');
}
});
$('.purchase li:nth-child(' + id + ') a').click();
debugger
});
</script>
Now my problem is in first time when i call partial view as a static version javascripts in partialview fires normally.
But when i call partialview inside a javascript code dynamically javascripts in the same partial view are not firing.
Please could anyone can help me to solve this issue?

Related

MVC builds html page but does not show it

I have a problem concerning Asp.net MVC.
I have an Index.cshtml page with the following javascript
$('#employeeTable tbody').on('dblclick', 'tr', function() {
var mitarbeiterId = table.row(this).data().Id;
$.post('#Url.Action("IndexCompletion")', { id: mitarbeiterId });
});
This basically just gets me the id of an employee and calls this ActionResult in my Controller
[HttpPost]
public ActionResult IndexCompletion(int id)
{
Mitarbeiter ma = new LeistungserfassungService.LeistungserfassungService().GetMitarbeiterById(id);
return View("IndexCompletion", new IndexCompletionViewModel{Mitarbeiter = ma});
}
Now i hoped that this will show me the following page:
#model Leistungserfassung.Models.IndexCompletionViewModel
#{
ViewBag.Title = "Completion";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="content">
<h2>Completion</h2>
#Model.Mitarbeiter.Nachname
</div>
But what happens now is, it builds the page successfully, as i can see on the networking tab in Google Chromes dev tools, but does not redirect to it.
Also when i directly try to navigate to this .cshtml file, the browser tells me it can not be found.
Does anyone have an idea of what could be the problem on this?
I am very new to javascript so i am grateful for any advice!
Thanks in advance and sorry for the german parts in my code.
You're making an async ajax call to the server using JavaScript this means JavaScript needs to redirect the user to another page. So, in order for this to happen your controller post method should return a response to JavaScript (most likely JSON) which will have a redirect link (key, value) item to then redirect.
I hope this helps you.
var jsonObj = JSON.stringify({
'id': mitarbeiterId
});
$.ajax({
url: '#Url.Action("IndexCompletion")',
type: "Post",
data: jsonObj,
async: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#divForReturnedViewFromController").html(msg);
},
});
Thanks for your help guys.
Now that i understand that $.post creates an AJAX call, I changed my code to create a form on Doubleclick and submit it with my Id.
(Which is the far better way to solve this problem)
$('#employeeTable tbody').on('dblclick', 'tr', function () {
var mitarbeiterId = table.row(this).data().Id;
$('<form action=#Url.Action("IndexCompletion") method="POST">' +
'<input type="hidden" name="id" value="' + mitarbeiterId + '">' +
'</form>').submit();
});
This works great. Thanks again for your help.

Add javascript function to wordpress page

I have a page that locates a link inside it and when that link is clicked it should save some data in database.
Besides, I have a file named "add.php" that communicates with the DB and operates well.
In my wordpress page I have added below codes for accessing the add.php file and send some parameters to it.
<a href="javascript:add(true);" >Click Me</a>
<script type="text/javascript">
function add(b){
$(document).ready(function(){
var result = $.ajax({
type: "POST",
url: "add.php",
data: { add: b }
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert( "No such data exists: " + textStatus );
});
});
}
</script>
I had this exact code in an html file and it worked smoothly. but it doesn't work on wordpress page like that.
Plus, the problem is that when I click the link -Click Me- it doesn't do anything.
please tell me where the problem is and how to solve it ?
I would recommend you to use this:
<a href="#" data-add="true" class='hitClick'>Click Me</a>
<!--use data* attributes to pass specific data -->
now in your function:
function add() {
event.preventDefault(); //<------make sure to add it.
var result = jQuery.ajax({
type: "POST",
url: "add.php",
data: {
add: jQuery(this).data('add')
}
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert("No such data exists: " + textStatus);
});
}
jQuery(document).ready(function(){
jQuery('.hitClick').on('click', add); // bind the click and use as callback
});

jQuery $.ajax succeed but serv doesn't receive any data

I work on a pagination system that wouldn't reload the whole page but just refresh the contents.
I retrieve the requested page with the value contained in a ID and want to send it to the server for the process.
The success is reached but my php script does not recognize the $_POST['page'] value.
Here is the JS:
$(document).ready(function()
{
$('#containerWrapper').on('click', '.holder a', function (event) {
var page = $(this).attr('id');
var url = "cart.php";
event.preventDefault();
// Launch of the Ajax query to refresh the current page
$.ajax({
url: "cart.php",
type: "POST",
data: {page: page},
success: function()
{
alert('Success, delivered page: ' + page);
$('#containerWrapper').load(url + " #containerWrapper");
}
});
});
});
Here the PHP, which i think isn't the real problem:
if (isset($_POST['page']) && ($_POST['page'])>0 && ($_POST['page'])<= $nbPages)
{
$cPage = htmlspecialchars($_POST['page']);
}
I've ready many topics but haven't found any relative problem for the now.
You really have too much code, it is not necessary for your purposes to bury a load() statement in an AJAX call. You could simply do this -
$(document).ready(function(){
$('#containerWrapper').on('click', '.holder a', function (event) {
event.preventDefault();
var url = "cart.php";
var page = $(this).attr('id');
$('#containerWrapper').load(url + " #containerWrapper", {page: page});
});
});
load() does allow you to send data to the requested page via a second arguement.

"Autocomplete is not a function" Javascript error

In my Grails project (version 2.2.1) I'm using the following Javascript code in two different GSP pages.
<g:javascript>
$(document).ready(function() {
$.ajax({
type: "GET",
url: "/medicalOfficeManager/Patient/getAllPatients",
dataType: "json",
success : function(response) {
//Create a map.
var data =
$.map(response, function(item){
console.log("id: " + item.id);
console.log("name: " + item.surname + " "+ item.name);
return{
id: item.id,
value: item.surname + " " + item.name
}
});
$("#patient_textField").autocomplete({
source: data,
select: function (event, ui){
console.log("selected id:" + ui.item.id);
console.log("selected name:" + ui.item.value);
//when a country is selected(ie: type China and press enter),
//change the value of hidden field to the country's id.
$('#patient_id').val(ui.item.id);
console.log("patient value = "+ $('#patient_id').val());
}
});
}
});
});
</g:javascript>
In one GSP everything works as expected, in another one, looking at Javascript console, I have the following error:
$(...).autocomplete is not a function
I've read this discussion, but it does not work for me.
Any suggestion?
EDIT: I've noticed that the only difference betweeen pages is that, in the not working one, it is loaded the bundle-bundle_core_head.js, but I don't see where it is loaded in gsp page...
EDIT2: there was a component loading in other gsp that includes an earlier version of JQuery and JQuery UI, but I need that component because, if I comment it, another field that allows me to choose date and time does not work. Is it possible to use both?
The autocomplete function is likely provided by a jQuery plugin that you are including in one page, but not the other. View the source of each page and compare the <script> elements in each.

How to bind a controls data using jQuery and Static Page Method?

Goal: Call a server side method asynchronously from changing a dropdown to get data and populate a separate listbox not using UpdatePanels.
Currently I'm using a static ASP.NET page method asynchronously using jQuery and an ajax call as shown in this post (How to wire up a DropDownList to make AJAX calls to the server?) and it is working well.
The whole purpose was to prevent using the UpdatePanel tangled mess that I had been in previous years and this seems to be a good alternative. What I didn't realize is that the page method has to be static and you can not access any of the page's controls or context. So trying to make this call from a dropdown selection to populate another control's data is not possible. I can't see the other controls.
So what I'd like to do before I give up and go back to updatepanels is try to do 1 of the following:
Have my static page method return a json string with my collection data that I then use in the original jQuery method wired up to the change method of the dropdown to populate the separate listbox.
Same as above but return a .NET IList<> or comparable if returning json is not a good idea.
Point is I want that static method to return the needed data to bind to my listbox control. However I don't know how to do this. Here is my current jQuery method:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the control.
$("<%= MyDDL.ClientID %>").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
});
</script>
Here is the original dropdown:
<asp:DropDownList ID="MyDDL" runat="server" Width="340px" />
Here is the control that needs populated based on the selection of the dropdown after calling the static method named MyDDL_SelectedIndexChanged:
<asp:ListBox ID="ListBox2" runat="server" Width="340px" SelectionMode="Multiple" />
Here is my current static page method:
[WebMethod]
public static string MyDDL_SelectedIndexChanged()
{
var myClass = new MyClass()
var data = myClass.GetDataCollection()
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonString = serializer.Serialize(data);
}
Is there a way to take this returned data and bind it in the jQuery method above? My bailout is to go back to using an UpdatePanel where my server-side method can access other controls, but I really do not want to do this.
There is a javascript project called jsRender that may be what you need:
http://weblogs.asp.net/stevewellens/archive/2011/12/01/goodby-jquery-templates-hello-jsrender.aspx
I actually was looking for a more complete exaample and have the solution working with the code below:
$(document).ready(function () {
MyDDL_OnChangeHandler();
});
function MyDDL_OnChangeHandler() {
// Add the page method call as an change handler for the MyDDL DropDownList.
// This will call the static page method, and use the returned results to populate the 'MyListBox' listbox control.
$('#<%=MyDDL.ClientID %>').change(function () {
var val = $(this).val();
var text = $(this).children("option:selected").text();
var $lbxCtrl = $('#<%=MyListBox.ClientID %>');
$lbxCtrl.attr('disabled', 'disabled');
$lbxCtrl.empty();
$lbxCtrl.append('<option value="0">< Loading Please Wait... ></option>');
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'ID':'" + val + "', 'Name':'" + text + "'}",
success: function (data) {
$lbxCtrl.removeAttr('disabled');
$lbxCtrl.empty();
if (data.d == null) {
return;
}
$.each(data.d, function (i, data) {
$users.append('<option value="' + data.Value + '">' + data.FullName + ' (' + adUser.data+ ')' +'</option>');
});
},
error: function () {
$lbxCtrl.empty();
$lbxCtrl.append('<option value="0">< Error Loading Data ></option>');
alert('Failed to retrieve data.');
}
});
});
As Michael B mentioned in the comments, you can handle any data returned from the ajax call by using success:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the control.
$("#<%= MyDDL.ClientID %>").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// do stuff with the "data" that is returned
},
error: function(data) {
// handle any errors here
}
});
});
});
</script>

Categories