How to render MVC 4 view on slickgrid double click via Javascript - javascript

I am using MVC4 along with slickgrid to display data to the user. I am trying to implement the ability to double click on a slickgrid row and have the page go to another view, but all I am able to get is the HTML returned to the client, but not rendered.
I am doing,
grid.onDblClick.subscribe(function (e, args) {
$.get(
"MapSetEdit/Edit/",
{ 'mapSetId': 1 }
);
});
and I have also tried:
grid.onDblClick.subscribe(function (e, args) {
$.ajax({
type: "GET",
url: "MapSetEdit/Edit/",
dataType: 'text',
data: {'mapSetId': 1}
})
.fail(function () {
console.log("Error retreiving map list.");
});
});
All this does is return the html to the browser but never renders it. How do I make a javascript request so that I am able to actually render the view. I think I am missing something obvious here as I am new to javascript and mvc.

You should render the returned HTML with jQuery. For example:
grid.onDblClick.subscribe(function (e, args) {
$.ajax({
type: "GET",
url: "MapSetEdit/Edit/",
dataType: 'text',
data: {'mapSetId': 1}
})
.succes(function(data){
var someemptydiv = $("#myEmptyDiv");
someemptydiv.html(data);
})
.fail(function () {
console.log("Error retreiving map list.");
});
});

I was able to do what I needed with:
grid.onDblClick.subscribe(function (e, args) {
window.location = '/MapSetEdit/Edit/?mapSetId=1'
});

Related

Calling [HTTPPost] from Javascript ASP.NET

I am using a method in my controller which imports data from an API. This method I am wanted to be called from two locations. First the view (currently working) and secondly a javascript function.
Start of controller method:
[ActionName("ImportRosters")]
[HttpPost]
public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
{
var authenticator = Authenticator(id);
var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);
var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id)
.ToDictionary(x => x.Id);
Javascript Function:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster, ActualLength, RosterLength }
});
SiteIDRoster = null;
location.reload();
$("#btnRunDeputyNow").modal("hide");
toast.show("Import Successful", 3000);
});
All values are being set but i am getting a 404 error on the url line
POST https://example.org/deputy/PerformImportRosterData 404 ()
I need a way to be able to call this c# method from both html and JS
This can be done if you will modify the URL in your AJAX. It should look something like
url: '<%= Url.Action("YourActionName", "YourControllerName") %>'
or
url: #Url.Action("YourActionName", "YourControllerName")
one more thing, I don't see if you do anything with the result of the call. your script does not have success part
success: function(data) {//do something with the return}
and would be very helpful to have error handler in your call.
full example on how AJAX should look like:
$.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
success: function (data, status, jqXHR) {
$("#container").html(data);
alert("Local success callback.");
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
})
For a good tutorial on AJAX read this document
Change after Comment:
my current code is below:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
data: { SiteIDRoster, ActualLength, RosterLength },
success: function(data) {
console.log(data);
console.log("TESTHERE");
}
});
}
UPDATE:
Noticed one more thing. Your parameters in the controller and AJAX do not match. Please try to replace your a few lines in your AJAX call with:
url: "/deputy/PerformImportRosterData",
data: { id: yourIDValue, actualLength: youractualLengthValue,
rosterLength :yourrosterLengthValue }
remember to set all variable values in javascript , if they have no values set them = to null.
Can you try copy paste code below
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});
And let me know if it wall cause any errors.
After attempting to solve for a few days, I created a workaround by creating two methods for importing the data. one for the httpPost and the second for import calling from javascript.
Not a great solution but it works. Thanks for your help Yuri

jQuery.when() doesn't seem to be waiting

I need to make a server side call when a user does something in the DOM (click a checkbox, select a dropdown, etc. This is the series of events:
User clicks a checkbox (or something)
A spinner fades in and the UI becomes unavailable
The server side call is made, and gets back some JSON
A label in the UI is updated with a value from the JSON
The spinner fades out and the UI becomes available again
The problem I'm having is that 4 and 5 often get reversed, and the spinner fades out sometimes 2 or 3 seconds before the label is updated.
I'm trying to use .when() to make sure this isn't happening, but I don't seem to be doing it right. I've been looking at this thread, and this one, and jquery's own documentation.
Here's where I'm at right now...
function UpdateCampaign() {
$('#overlay').fadeIn();
$.when(SaveCampaign()).done(function () {
$('#overlay').fadeOut();
});
}
function SaveCampaign() {
var formData =
.... // get some data
$.ajax({
url: '/xxxx/xxxx/SaveCampaign',
type: 'GET',
dataType: 'json',
data: { FormData: formData },
success: function (data) {
var obj = $.parseJSON(data);
.... // update a label, set some hidden inputs, etc.
},
error: function (e) {
console.log(e)
}
});
}
Everything works correctly. The server side method is executed, the correct JSON is returned and parsed, and the label is updated as expected.
I just need that dang spinner to wait and fade out until AFTER the label is updated.
The issue is because you're not giving $.when() a promise. In fact you're giving it nullso it executes immediately. You can solve this by returning the promise that $.ajax provides from your SaveCampaign() function like this:
function SaveCampaign() {
var formData = // get some data
return $.ajax({ // < note the 'return' here
url: '/xxxx/xxxx/SaveCampaign',
type: 'GET',
dataType: 'json',
data: { FormData: formData },
success: function (data) {
var obj = $.parseJSON(data);
// update a label, set some hidden inputs, etc.
},
error: function (e) {
console.log(e)
}
});
}
I know its answered by Rory already. But here's mine promise method, it works fine always and instead of using success and error uses done and fail
var jqXhr = $.ajax({
url: "/someurl",
method: "GET",
data: {
a: "a"
});
//Promise method can be used to bind multiple callbacks
if (someConditionIstrue) {
jqXhr
.done(function(data) {
console.log('when condition is true', data);
})
.fail(function(xhr) {
console.log('error callback for true condition', xhr);
});
} else {
jqXhr.done(function(data){
console.log('when condition is false', data);
})
.fail(function(xhr) {
console.log('error callback for false condition', xhr);
});
}
Or if I want a common callback other than conditional ones, can bind directly on jqXhr variable outside the if-else block.
var jqXhr = $.ajax({
url: "/someurl",
method: "GET",
data: {
a: "a"
});
jqXhr
.done(function(data) {
console.log('common callback', data);
})
.fail(function(xhr) {
console.log('error common back', xhr);
});

MVC / AJAX send data to controller and load response in same view

I have a page with three form fields (2 textbox, 1 dropdown), a submit button and a 'refresh' link. I want to be able to click the link and pass two form textbox values to a controller action, and get a list of values to populate the dropdown box. I do not want to submit the form at this stage.
At the moment, I have managed to call the controller action from the link click, but I cannot pass the two form field values in for some reason. Also, the return JSON just takes me to a new page instead of populating my dropdown list. Any pointers would be great as I am new to javascript and MVC. My code is below;
Controller
public ActionResult Find(AddressFormViewModel model)
{
...
var temp = new List<OptionModel>();
temp.Add(new OptionModel {Id = item.Id, Value = item.desc});
return Json(temp, JsonRequestBehavior.AllowGet);
}
HTML
#Html.TextBoxFor(x => Model.HouseNameInput, new { id = "HouseNameInput" })
#Html.TextBoxFor(x => Model.PostCodeInput, new { id = "PostCodeInput" })
#Html.ActionLink("Find","Find", "Address", new { houseInput = Model.HouseNameInput, postcodeInput = Model.PostCodeInput }, new { htmlAttributes = new { #class = "Find" } })
#Html.DropDownListFor(x => Model.AddressOption, Enumerable.Empty<System.Web.Mvc.SelectListItem>(), "-- Loading Values --", new {id = "AddressOptions"})
And lastly, my Javascript method which is retrieving the data from the controller action but not populating the dropdown list (it displays the results in a new page). It is also not successfully sending the form values to the controller action.
$(function () {
$('.Find').click(function (evt) {
$.ajax({
type: 'POST',
url: '#Url.Action("Find","AddressFormSurface")',
cache: false,
async: true,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
houseNameInput: $("#HouseNameInput").value,
postCodeInput: $("#PostCodeInput").value
},
success: function (data) {
if (data.exists) {
var ddl = $('#AddressOptions');
ddl.empty();
data.each(function () {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl);
});
}
},
error: function (req) {
}
});
// we make sure to cancel the default action of the link
// because we will be sending an AJAX call
return false;
});
});
You have a number of errors in your script which will cause it to fail.
You specify contentType: "application/json; charset=utf-8", but do
not stringify the data (the option should be removed)
You need to use .val() (not .value) to get the values of the
inputs
The data you receiving does not contain a property named exists so
the if block where you append the options will never be hit
In addition it is unnecessary to generate your link using #Html.ActionLink() (your adding route values based on the initial values of the model). Instead just create it manually
Find
and change the script to
var ddl = $('#AddressOptions'); // cache it
$('#find').click(function () { // change selector
$.ajax({
type: 'GET', // its a GET, not a POST
url: '#Url.Action("Find","AddressFormSurface")', // see side note below
cache: false,
async: true,
dataType: "json",
data: {
houseNameInput: $("#HouseNameInput").val(),
postCodeInput: $("#PostCodeInput").val()
},
success: function (data) {
if (!data) {
// oops
return;
}
ddl.empty();
$.each(data, function(index, item) {
$(document.createElement('option'))
.attr('value', item.Id)
.text(item.Value)
.appendTo(ddl);
// or ddl.append($('<option></option>').text(item.Value).val(item.Id));
});
},
error: function (req) {
....
}
}
});
Side note: Also check the name of the controller. Your Html.ActionLink() suggests its AddressController but your script is calling AddressFormSurfaceController

ajax request not sending any data ASP.NET MVC project with jQuery

I'm fairly new to asp.net MVC but am baffled as to why my request isn't working.
I'm trying to send an ajax request with jquery as per:
jQuery(function ($) {
var total = 0,
share = $('div.share'),
googlePlusUrl = "https://plusone.google.com/_/+1/fastbutton?url=http://bookboon.com" + $(location).attr('pathname');
setTimeout(function() {
$.ajax({
type: 'GET',
data: "smelly",
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});
}, 4000);
And set a line in my RouteConfig as:
routes.MapRoute(null, "services/{site}/proxy", new { controller = "Recommendations", action = "Proxy" });
The markup has a data-attribute value as:
<div class="share" data-proxy="#Url.Action("Proxy", "Recommendations")">
And my Proxy action method starts with:
public ActionResult Proxy(string junk)
The problem is that the junk parameter is always null. I can see in the debug output that the route seems to correctly redirect to this method when the page loads (as per jQuery's document ready function), but I cannot seem to send any data.
I tried sending simple data ("smelly") but I don't receive that neither.
Any suggestions appreciated!
The model binder will be looking for a parameter in the request called junk, however you're sending only a plain string. Try this:
$.ajax({
type: 'GET',
data: { junk: "smelly" }, // <- note the object here
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});

Ajax call to delete and refresh list not working

I am implementing an Ajax call to the server to delete a post from a li. The delete is working fine, but I need to manually get out from the list page and when I get back the list is updated. What I am trying to achieve, is that when the button that deletes the item, also refreshes the list. I added the following code but is not refreshing :(.
function deleteThisPost() {
//alert($('#myPostIDStorage').val())
$.ajax({
type: 'GET',
data: 'myPostIDValue=' + $('#myPostIDStorage').val(),
url: 'http://wander-app.org/deletePosts.php',
timeout: 5000,
success: function (data) {
alert('Post Deleted!');
},
error: function () {
alert('Error Deleting Post');
}
});
return false;
$('#myPost').listview("refresh");
};
Your ajax call works fine as you can see there. You should take a notice that if you return anything from a function it is no longer executed. The code that you provided below $( '#myPost' ).listview( "refresh" ); will be never examined.
What you probably want to do is
function deleteThisPost() {
//alert($('#myPostIDStorage').val())
$.ajax({
type: 'GET',
data: 'myPostIDValue=' + $('#myPostIDStorage').val(),
url: 'http://wander-app.org/deletePosts.php',
timeout: 5000,
success: function (data) {
alert('Post Deleted!');
},
error: function () {
alert('Error Deleting Post');
}
});
$('#myPost').listview("refresh");
return false;
};
According to your question if you want a dialog box with cancel and confirm button you can do
if(confirm('Do you want to delete?') == true) {
alert('Deleted');
}

Categories

Resources