Calling action from jquery correctly? - c#

I've never used ajax and I'm just try to see if this will call the method from my controller and give me the desired result. The javascript debugger in VS doesn't seem to be working at the moment. Does this look right?
$("form").submit(function() {
var hasCurrentJob = $.ajax({
url: 'Application/HasJobInProgess/#Model.ClientId'
});
});
controller method
public Boolean HasJobInProgress(int clientId)
{
return _proxy.GetJobInProgress(clientId).Equals(0);
}
Update
$("#saveButton").click(function() {
var hasCurrentJob = false;
$.ajax({
url: '#Url.Action("HasJobInProgress","ClientChoices")/',
data: { id: #Model.ClientId },
success: function(data){
hasCurrentJob = data;
}
});
if (hasCurrentJob) {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
}
});

Try to use the Url.Action HTML Helper method when calling an action method. This will get you the correct url to the action method. You dont need to worry about how many ../ to add/
$(function(){
$("form").submit(function() {
$.ajax({
url: '#Url.Action("HasJobInProgess","Application")',
data: {clientId: '#Model.ClientId'},
success: function(data) {
//you have your result from action method here in data variable. do whatever you want with that.
alert(data);
}
});
});
});

Related

Asp .net core project: Ajax call can't reach controller (400 status code)

I'm refactoring my ASP .net core project and I want to make use of some Ajax calls, but I'm facing the following problem: when I try to send a request to a method in a controller of my project but it doesn't work.
I have a modal with the following button:
<button onclick="reviewRestaurant(#item.RestaurantId)" class="btn btn-outline-primary">Add review</button>
the reviewRestaurant() function looks like this:
function reviewRestaurant(restaurantId) {
let rating = $("input[type=radio]:checked").val();
let review = $('textarea').val();
let data = { restaurantId, rating, review };
$.ajax({
type: "POST",
url: `/Restaurants/Review`,
data: JSON.stringify(data),
success: function (res) {
// TODO: work on this later
},
error: function (err) {
console.log(err);
}
});
}
And the method that I wanna call in the Restaurants controller looks like so:
[Authorize]
[HttpPost]
public async Task<IActionResult> Review(int restaurantId, string rating, string content)
{
var username = this.User.Identity.Name;
await this.restaurantsService.Review(restaurantId, username, rating, content);
return this.RedirectToAction("Details", new { id=restaurantID });
// the output of this method will be refactored later once I manage to get to it
}
The problem is I cannot reach the Review method in the controller. I get the 400 status code and I don't know how to fix it. I tried using DTO and [FormData] attribute for the method parameters and tried passing the data without stringifying it still nothing works.
If anyone can help me I would be very grateful. I'm relatively new to ajax calls and simply cannot see where my mistake is.
You can try this solution:
Create a common class for your parameters (int restaurantId, string rating, string content) and use FromBody. => Review([FromBody] YourClassName)
And write this parameters in your ajax code.
contentType: 'application/json; charset=utf-8',
data: 'json'
I hope it will help you.
Here is a working demo which I test.
#section Scripts
{
<script>
function reviewRestaurant(restaurantId) {
let rating = $("input[type=radio]:checked").val();
let content = $('textarea').val();
let data = { restaurantId, rating, content };
$.ajax({
type: "POST",
url:'/Restaurants/Review',
data: data,
success: function (res) {
// TODO: work on this later
},
error: function (err) {
console.log(err);
}
});
}
</script>
}

Trying to Get Data using Ajax call to Controller method MVC My code Attached

I am calling jquery function on dropdown value change jquery method is ,
function MyFunction() {
alert($('#DDlSurvey').val());
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "GET",
dataType: "json",
success: function (data) {
// loadData(data);
alert(data)
alert("Success");
},
error: function () {
alert("Failed! Please try again.");
}
});
//$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
Function I'm calling and I am getting dropdown value alert
Now, Function that I am calling is "GetSelectedQuestion" in controller "ConductSurveyController"
Method is like ,
[HttpPost]
public JsonResult GetSelectedQuestion(int prefix)
{
List<SelectList> Questions=new List<SelectList>();
// Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
SurveyAppEntities ObjectSur = new SurveyAppEntities();
// Questions = ObjectSur.Surveys.Where(a => a.ID.Equals(prefix)).toToList();
I don't think this method is calling as I am getting error
"Failed! Please try again"
From my script.
Hopes for your suggestions
Thanks
var e = from q in ObjectSur.Questions
join b in ObjectSur.SurveyQuestions on q.ID equals b.QuestionID where b.SurveyID.Equals(prefix)
select q ;
return new JsonResult { Data = e, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I think you are using controller name straight forward. your ajax code be something like this.
var PostData= { prefix: $('#DDlSurvey').val() }
var ajaxOptions = {
type: "GET",
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',//Actionname, ControllerName
data: PostData,
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (result) {
}
};
$.ajax(ajaxOptions);
Your method in your controller is decorated with HttpPost, while in your ajax you have specified the type of your request is get . You can either change your method to get like this:
[HttpGet]
public JsonResult GetSelectedQuestion(int prefix)
{
}
Or change your request type to post in your Ajax call:
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "Post",
Also the Controller is redundant in ConductSurveyController, you need to remove it and simply call it as ConductSurvey:
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',

Making an Ajax call to a partial view after ajax success

I have a partial view that contains all my buttons and it needs to display updated values after a form is submitted. At the submission I already have it rendering another partial view, is there a way to make it work where on success of that one being rendered it re-renders. Here is the code I am trying to get to work now based on what I've seen in other places.
jQuery in my view:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#ChangeGrade').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#HeatGradeDiv').find('input[name="grade"]').first().val();
var newname = $('#HeatGradeDiv').find('input[name="updatedGrade"]').first().val();
var heatname = $('#HeatGradeDiv').find('input[name="hiddenHeat"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
grade: origname,
updatedGrade: newname,
hiddenHeat: heatname
},
url: '#Url.Action("ChangeGrade","Home")',
success: function (result) { success(result); }
});
});
function success(result) {
$('#HeatGradeDiv').dialog('close');
$("#Partial_Chem_Analysis").html(result);
//ajax call I'm trying to get working
$.ajax({
type: "POST",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
}
});
</script>
Here is the controller method I'm calling. When I run it now it is not getting hit.
public ActionResult ButtonsPartial()
{
ButtonsModel B = new ButtonsModel();
B.GetData(searchQ);
return PartialView(B);
}
Any help is appreciated.
If you attach it to a debugger such as (chrome developer tools or firebug) are you seeing any http or js errors?
It looks like you might need to make it a GET rather than POST...
$.ajax({
type: "GET",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});

Calling a C# method with jquery

I am trying to call a method with jQuery on a button click.This is waht I have so far:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
[WebMethod]
public void AddToCartHack(string url)
{
GeneralHelperClass.URL = url;
}
What I am trying to do here is when I click the link with class add to cart I want to call the method AddToCartHack and pass it the curent URL as a parameter.
I must be doing something wrong because it seems that AddToCartHack is not being called.
What am I doing wrong?
There are quite a lot of issues with your code, I don't know where to start. So let's conduct an interactive refactoring session with you (if you don't care about my comments but just want to see the final and recommended solution, just scroll down at the end of answer).
First: you don't seem to be canceling the default action of the anchor by returning false from the .click() event handler. By not doing this you are actually leaving the browser perform the default action of the anchor (which as you know for an anchor is to redirect to the url that it's href attribute is pointing to. As a consequence to this your AJAX call never has the time to execute because the browser has already left the page and no more scripts are ever running). So return false from the handler to give your AJAX script the possibility to execute and stay on the same page:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
return false;
});
Second: You have specified contentType: 'application/json' request header but you are not sending any JSON at all. You are sending a application/x-www-form-urlencoded request which is the default for jQuery. So get rid of this meaningless parameter in your case:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
dataType: "json"
});
return false;
});
Third: You have specified that your server side code will return JSON (dataType: 'json') but your server side code doesn't return anything at all. It's a void method. In ASP.NET MVC what you call C# method has a name. It's called a controller action. And in ASP.NET MVC controller actions return ActionResults, not void. So fix your contoller action. Also get rid of the [WebMethod] attribute - that's no longer to be used in ASP.NET MVC
public class AccountController: Controller
{
public ActionResult AddToCartHack(string url)
{
GeneralHelperClass.URL = url;
return Json(new { success = true });
}
}
Fourth: you have hardcoded the url to the controller action in your javascript instead of using server side helpers to generate this url. The problem with this is that your code will break if you deploy your application in IIS in a virtual directory. And not only that - if you decide to modify the pattern of your routes in Global.asax you will have to modify all your scripts because the url will no longer be {controller}/{action}. The approach I would recommend you to solve this problem is to use unobtrusive AJAX. So you would simply generate the anchor using an HTML helper:
#Html.ActionLink(
"Add to cart",
"AddToCartHack",
"Account",
null,
new { #class = "AddToCart" }
)
and then unobtrusively AJAXify this anchor:
$('a.AddToCart').click(function () {
var link = document.URL;
$.ajax({
type: 'POST',
url: this.href,
data: { url : link }
});
return false;
});
Fifth: You seem to be employing some document.URL variable inside your .click() handler. It looks like some global javascript variable that must have been defined elsewhere. Unfortunately you haven't shown the part of the code where this variable is defined, nor why is it used, so I cannot really propose a better way to do this, but I really feel that there's something wrong with it. Or oh wait, is this supposed to be the current browser url??? Is so you should use the window.location.href property. Just like that:
$('a.AddToCart').click(function () {
$.ajax({
type: 'POST',
url: this.href,
data: { url : window.location.href }
});
return false;
});
or even better, make it part of the original anchor (Final and recommended solution):
#Html.ActionLink(
"Add to cart",
"AddToCartHack",
"Account",
new { url = Request.RawUrl },
new { #class = "AddToCart" }
)
and then simply:
$('a.AddToCart').click(function () {
$.ajax({
type: 'POST',
url: this.href
});
return false;
});
Now that's much better compared to what we had initially. Your application will now work even with javascript disabled on the page.
place script method this way as shown below
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Add Success and error function to check your ajax functionality
...
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
alert('success');
},
error:function(){
alert('error');
}
});
....
If this is Asp.Net webforms you will need to make the webmethod static or the method cannot be accessed through JavaScript.
$(document).ready(function () {
$.ajax({
url: "Testajax.aspx/GetDate",
data: "f=GetDate",
cache: false,
success: function (content) {
$('#tableData').append('My Dear Friend');
alert(content);
},
failure: function (response) {
alert("no data found");
}
});
});

how to replace div content with $.ajax like a $.post

The Objective:
Change my $.post to an $.ajax in order to syncronize it and display the message until request has finished.
I would like to know exactly how I could do that with an ajax request, my big problem is when I try to replace div content as what I have done it here using $.post
The code:
The view
function NewVersion() {
$.ajax({
url: "/Valoration/NewVersion",
type: "POST",
async: false,
success: function (data, status, xhr) {
if (data.success) {
$.post(data.hvmHeaderPartialView, function (partial) { $('#divHvmHeader').html(partial); });
MessageNewVersionSucced();
}
},
error: function (xhr, status, err) {
alert(err);
}
});
The controller
public ActionResult HvmHeaderPartialView()
{
return PartialView("_HvmHeaderPartialView,", DetailHvmModel);
}
private ActionResult NewVersion()
{
var result = hvmService.addNewVersion(hvm);
var HvmHeaderPartialView = Url.Action("HvmHeaderPartialView,");
return Json(new
{
success = result,
hvmHeaderPartialView= HvmHeaderPartialView,
});
}
Do you need to keep it async=false?
You could use $.load() to replace div content instead of using $.post. For example:
$('#divHvmHeader').load('ajax/test.html');
With a callback function:
$('#divHvmHeader').load('/Valoration/NewVersion', function() {
MessageNewVersionSucced();
});
Note: MessageNewVersionSucced will execute only after the ajax call to '/Valoration/NewVersion' completed.
You stated
Change my $.post to an $.ajax in order to syncronize it...
I am not sure if you are using jQuery 1.8 but the jQuery site states
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is
deprecated; you must use the complete/success/error callbacks.
Your request will not be performed synchronously. This may be the root of your problem.

Categories

Resources