ASP.NET MVC submit empty string to WebApi Controller on jquery serialize() - c#

I'm trying to POST data from ASP.NET MVC View to WebApi Controller via j Query $.post(), but I'm always receiving just empty string (what's interesting - this work fine with Web Forms).
Here is JS.
$("#searchbtn").click(function () {
var ser = $("div#hotels").serialize();
$.post('/api/hotelsavailablerq', { '': ser });
});
Here is how ApiController signature look like:
[HttpPost]
public void PostHotelsAvailableRq([FromBody] string q)
View using just pure HTML forms - div, select, input type=text. Nothing Binded from model.

try another:
$.ajax({
url: '/api/hotelsavailablerq',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json'
data: JSON.stringify(ser)
});

Please try the below code to hit the controller. Make sure there is hotelsavailablerq action method in api controller.
$("#searchbtn").click(function () {
$.ajax({
url: '/api/hotelsavailablerq',
type: 'POST',
data: $('div#hotels').serialize(),
success: function (result) {
});});

Well, I found answer - RTFM.
When I read carefully jQuery documentation about serizlization, I found that:
1. <form> tag should exist.
2. Each control should have name attribute.
All these things has by default in web form, but in MVC I should add its manually.

Try
$.post('/api/hotelsavailablerq', { 'q': ser });
string q should be of the same type which you are sending from the jQuery.

Related

Ajax post not working MVC 5

I'm trying to post data into a controller but it doesn't seems to work, I need the post to include the content of the view into a div when done but I cant quite achieve it
Here's my js function:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: "Student/Schedule",
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').load(a);
}
});
}
And, here's my controller:
public ActionResult Schedule(String number)
{
return View(number);
}
I am a noob in MVC and C#, so any help is welcome.
There are somethings that you should fix to solve the problem.
Change Url to "/Student/Schedule"
You are using "Student/Schedule" as url, so you are trying to call an action named "Student".
Add [HttpPost] to your action.
You should return PartialView("Schedule", number);.
When you use return View(number) it uses the string value of number as your view name. You should explicitly pass view name and model.
Use $('#schedule').html(a);
It's better to add an error function to your ajax call to be able to find errors:
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
//or you can put jqXHR.responseText somewhere as complete response. Its html.
}
Your action should return a Partial View, not a View.
Change your action to:
[HttpPost]
// by the way use string instead of String
public ActionResult Schedule(string number)
{
return PartialView("_Schedule", number);
}
Then, you'll need to create a partial view named _Schedule.cshtml.
Also, you need to change $('#schedule').load(a); to $('#schedule').html(a); And, I'd suggest that you use a Url.Action to set your url in your ajax call, like this:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: '#Url.Action("Schedule", "Student")',
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').html(a);
}
});
}
I had the same issue what i did was adding jquery.unobtrusive-ajax.js to my scripts

ajax call to c# mvc sends both post and get

I've looked at several solutions for making an ajax call and by not this issue mentioned anywhere i feel it might be something specific to the environment i'm working with.
My controller:
[HttpPost]
public ActionResult ChangeDefualtCC(string a)
{
return Json("ok");
}
[HttpGet]
public ActionResult ChangeDefualtCC()
{
return Json("ok");
}
JS:
$("nevermind").change(function () {
$.ajax({
type: "POST",
url: "/Account/ChangeDefualtCC",
dataType: "json",
data: {
a: "A"
},
success: function (data) { console.log(data)},
error: function (data) { console.log("error");}
});
});
The Controller code is never hit, and this is what i'm seeing in chrome after the ajax call:
EDIT 2: The page hits the [HttpGet] method.
EDIT:
I tagged Ektron as well because it is used in the project, and it is possible that it is affecting the call.
My Routes:
Update: I have tried using Get, as well as Post, and also returning back to the View I was in, I get the 302 everytime.
any ideas?
It looks like it finds the "get" because you don't have a parameter in that call. I think you might be missing the content type from your ajax call, so the model binder cannot parse the content of your post as a parameter.
$.ajax({
type: "POST",
url: "/Account/ChangeDefualtCC",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {
a: "A"
},
success: function (data) { console.log(data)},
error: function (data) { console.log("error");}
});
Your code seems to be absolutely correct.
This not be exact solution but try this may it work.
$("nevermind").change(function () {
$.post("/../Home/ChangeDefualtCC", { a: "A" }, function (data) {
console.log(data)
});
});
Our project is integrated with the CMS Ektron. We later discovered that Ektron is hit before the C# code, and has some affect to any url without a trailing url.
Thanks for all the help

Pass a collection to MVC controller via jquery

I'm using ASP.NET MVC3 with Jquery. I'm trying to pass my form elements back to the controller using something like this (Please note I removed success and error code for simplicity):
var formElements = $("#myForm").serialize();
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: {collection: formElements},
success:
error:
dataType: "json"
});
My question is what should the parameter in my controller method look like:
Here is my controller method:
public ActionResult SubmitChanges(WHAT GOES HERE?)
{
}
So what I'm really looking for is what should be the type of the parameter going into the controller method? I want to be able to retrieve the values of the form elements in the controller.
So here is what I did. I have about 20-30 elements on my form so I really didn't want to have to turn each one into a parameter or list them all out in the collection.
In the jquery, I did the following:
var formElements = $("#myForm").serialize();
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: { parms: formElements },
success:
error:
dataType: "json"
});
It then goes into my controller as a string:
public ActionResult SubmitChanges(string parms)
I then found a function to parse that string (seems to be working)
NameValueCollection qscoll = HttpUtility.ParseQueryString(parms);
This seems to work without listing out all of the form elements.
Assuming your form elements all correspond to your model (let's say it's MyModel), then it should simply be:
public ActionResult SubmitChanges(MyModel model)
{
}
MVC default model binding will do the rest :).
Make sure you change your data definition in the jQuery ajax method though, you've already serialized it. Just do:
data: formElements,
I'm assuming the following in your jQuery ajax method is a copy and paste error?
success:
error:
If it's not, then make sure you either remove it, or change them to:
success: function (result) {
//do something
},
error: function () {
//do something on error
}
The problem is that their is no model that corresponds to my form
elements.
Then you can have this:
public ActionResult SubmitChanges(int id, string name)
{
}
And then pass in the individual items:
var o = {
id = $("#id_elem_id").val(),
name = $("#name_elem_id").val()
}
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: JSON.stringify(o),
success:
error:
dataType: "json"
});
where id_elem_id and name_elem_id are the ids of your html elements. And add any additional parameters you need, just follow along.
You were almost there. Just get rid of the brackets around your data parameter:
var formElements = $('#myForm').serialize();
$.ajax({
type: 'POST',
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: formElements,
success: function(result) {
// handle the success of the AJAX request
},
error: function() {
// an error occurred
}
});

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");
}
});
});

Using PageMethods with jQuery

Simply put I want to call public static methods decorated with WebMethod attribute inside my code-behind C# file from jquery.ajax to get some json and other simple stuff (in different functions). But instead I'm getting whole page :'(
I'm not using asp.net AJAX though I'm developing for .NET 3.5 framework and using VS 2008. (There are some restrictions from client)
Please let me know if I can use page-methods with using asp.net ajax or If not what is other simple solution?
After much deliberations I found the problem. I was using jquery's editable plugin. This was source of the problem. When jeditable calls jquery's ajax it sets ajax options like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
success: function(result, status) {
if (ajaxoptions.dataType == 'html') {
$(self).html(result);
}
self.editing = false;
callback.apply(self, [result, settings]);
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
},
error: function(xhr, status, error) {
onerror.apply(form, [settings, self, xhr]);
}
};
so it was sending the things as simple html and to use this with page methods we need to setup the things so that it sends as json. So we need to add something to the settings like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: 'json', //Data Type
contentType: 'application/json; charset=utf-8', //Content Type
//....other settings
};
So I put two new properties in settings dataType and contentType and changed above to this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: settings.dataType,
contentType: settings.contentType,
//....other settings
};
Now another problem arised :( it was sending data (from submitdata property) as normal query-string which asp.net does not accept with json requests. So I had to use jquery's json plugin and change the way data is sent in ajax using following test on dataType:
if (settings.dataType == "json") {
if ($.toJSON) {
submitdata = $.toJSON(submitdata);
}
}
and it works like breeze!!!
Russ Cam posted this link in response to another question (so if this helps, go up vote his answer ;)):
Using jQuery to directly call ASP.NET AJAX Page Methods
Dave Ward has a series of posts that use jQuery directly with ASP.Net PageMethods, no MS Ajax UpdatePanel required. In particular this post will get you started.
I am not sure but i think WebMethods are accessible only through asp.net AJAX. I may be wrong though, because we dont use it that way at all. We do it in a slightly different way.
We have built a aspx page which accepts all our AJAX requests and passes them to the subsequent methods.
Server side code
If Not (Request("method") Is Nothing) Then
method = Request("method")
username = HttpContext.Current.User.Identity.Name.ToString
Select Case UCase(method)
Case "GETPROJECTS"
Response.ContentType = "text/json"
Response.Write(GetProjects(Request("cid"), Request("status")))
Exit Select
end select
end if
Client Side code [using jquery]
$.ajaxSetup({
error: function(xhr, msg) { alert(xhr, msg) },
type: "POST",
url: "Ajax.aspx",
beforeSend: function() { showLoader(el); },
data: { method: 'GetProjects', cid: "2", status:"open"},
success: function(msg) {
var data = JSON.parse(msg);
alert(data.Message);
},
complete: function() { hideLoader(el); }
});
Hope this helps.

Categories

Resources