JQuery getJSON in MVC - c#

I have the following JSon call that I want to call a method in Controller & accepts JSon object to update Partial View:
<script type="text/javascript">
function DoAjaxUpdate(btnClicked) {
btnClicked = $(btnClicked);
var $form = btnClicked.parents('form');
var url = '#Url.Action("Remove")';
$.getJSON(
url,
$form.serialize(),
function () {
if (data.htmlPartialView != null) {
return $("#divPartialView").load(obj.htmlPartialView);
}
});
return false;
}
</script>
Unfortunately, this isn't passing the data properly and instead appends it to the URL as a query string such as: http://www.myLink.com/MyController/Remove?dataID=1359&dataMember=1
Please help. Thanks

That's what happens with $("form").serialize(). It will serialize everything on the form and put it on the query string.
As long as your Remove action method takes an instance of the model that is on your original view, then it will be transformed using the values in the query string.
To send it as JSON, you'd have to use JSON.stringify():
JSON.stringify($form.serialize())

The callback need parameter,like this:
$.getJSON(
url,
$form.serialize(),
function (obj) {
if (obj.htmlPartialView) {
$("#divPartialView").load(obj.htmlPartialView);
}
});
by the way,if (obj.htmlPartialView) is same to if (data.htmlPartialView != null)

You are calling getJSON which sends the data as a GET request which uses the querystring. If you want to use the POST method, use (from the jQuery site):
$.post(url, data, function(data) {
});
or
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
More information: http://api.jquery.com/jQuery.post/

Related

Pass Query String Value into jQuery Ajax Call in ASP.NET

I have a webMethod with a single argument I am trying to call via jQuery Ajax. Now the argument is supposed to be the query string of the url in which I am making the ajax call. I don't know how to pass the query string as an argument into the method from the jQuery ajax. My Code is as follows
C# Method
[WebMethod]
public static string FollowUser(string userId)
{
//Code to follow user
//returns a string value
}
jQuery Ajax
$(document).ready(function() {
$("#btnFollow").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/FollowUser",
data: //how do I pass the query string here
contentType: "application/json; charset=utf-8", datatype: "json",
context: this,
success: function(msg) {
//I'm doing some stuff here
}
},
error: function(response) {
alert(response.d);
}
});
});
});
Someone help me out. Thanks.
You need to pass the data as part of the the URL or change the method to GET. When submitting an aJax post with data you are sending the data as part of the request body (form data). This won't be as a query string attribute but part of the content. Instead change the URL To include the data. Example.
Default.aspx/FollowUser?userId=user1
changing to a GET method will force the post parameters to be part of the query string instead.

Fill jquery array with server array?

on controller I have MODEL
public partial class CategoryModel
{
...
public int[] SelectedCustomerIds { get; set; }
}
passed to a View from a controller. How can i fill the jquery array by the Model.SelectedCustomerIds
<script type="text/javascript">
var selectedIds = []; << what to replace here
what you can do is u can first create object in jQuery and make a ajax call to server using AJAX and server side you will get tht object and you can simply transfer that object value to your model value!!
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: yourObject, //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (json) {//On Successful service call
var result = json.name;
$("#dvAjax").html(result);
},
error: ServiceFailed // When Service call fails
});
server side
using System.Web.Services;
[WebMethod()]
//[ScriptMethod()]
public static void SendMessage(CategoryModel yourModelObject )
{
}
You can use JSON.NET
<script type="text/javascript">
var selectedIds = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.SelectedCustomerIds))
If you want to use JavaScript side array pushing, then try this
in view put all array elements in hidden
#Html.Hidden("SelectedCustomerIds_"+i, Model.SelectedCustomerIds[i])
and in JavaScript
var selectedCustomerIds = [];
$('*[id*=SelectedCustomerIds_]').each(function () {
selectedCustomerIds.push($(this).val());
});
});

Passing a parameter from JavaScript to a controller

I am trying to pass a string value to a create item dialog, and am not sure on how to do it.
This is the code in my view:
JavaScript:
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}
View:
<td>#route</td>
<td>
Add
</td>
Controller:
public ActionResult Create(string routeName = "")
{
PopulateRouteInfoViewBag();
var newRoute = new RouteInformation();
newRoute.Name = routeName;
return View(newRoute);
}
I'm trying to take the value in #route and pass it over to the Create controller to have my dialog pop up with the passed in string value.
Use the ActionLink html helper method and pass the route variable like this.
#{
string route="somevaluehere";
}
#Html.ActionLink("Add","Create","YourControllerName",
new { routeName=route},new {#id="addLnk"})
Now handle the click event
$(function(){
$("#addLnk").click(function(e){
e.preventDefault(); //prevent normal link click behaviour
var _this=$(this);
//do your ajax call now
$.ajax({
url: _this.attr("href"),
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = 'someValidUrlHere'
else
$.facybox(data);
}
});
});
});
Also, You may consider building the path to the new page(action method) and return that as part of your JSON result and let the client read it from the JSON.
instead of appending the route variable value to the querystring, you may consider it as the part of message body.
There are two options. 1, use Url.Action("controllerName", "actionName", new {routeName = "your route name here"}) or 2, use the data property of the object passed into $.ajax.
For 2 your javascript would look something like
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
data: {
route: "your data here"
}
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}

Calling action from jquery correctly?

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

Passing Array to Action from a $.post

I am having trouble passing my array via a $.post.
The Javascript
var privIDs = [1,2,4,5];
$.post("/Home/GrantPrivilegesToUser", { privilegeIDs: privIDs }, function (data) {
alert("Data Loaded: " + data.success);
});
The Action
public ActionResult GrantPrivilegesToUser(int[] privilegeIDs)
{
return Json(new {success=true});
}
The action sees privilegeIDs as null. Any ideas?
You need to set jQuery.ajaxSettings.traditional = true; for you jQuery ajax setting. In jQuery 1.4 they changed the way items are serialized in a form post.
please see:
http://forum.jquery.com/topic/nested-param-serialization
And:
How can I post an array of string to ASP.NET MVC Controller without a form?
I use JSON to pass data as a string using the JSON2 library: http://www.json.org/js.html
var privIDs = [1,2,3,4,5];
var data = JSON.stringify({privilegeIDs : privIDs});
$.POST("/Home/GrantPrivilegesToUser", data, function (data) {
alert("Data Loaded: " + data.success);
});
And the action would use the WebMethod type:
[WebMethod]
public object Entry_GetFormOptions(string privilegeIDs)
{
return new {success=true};
}
There are both built-in and 3rd party functions for parsing the received JSON to access the privilege IDs.
Let me know if this does or does not help.
This is what I ended up doing. Might be helpful to someone...
var privIDs = [1,2,4,5];
$.ajax({
type: "POST",
url: "/Home/UpdatePrivileges",
data: { privilegeIDs: privIDs },
traditional: true,
success: function (json) {
alert(json.success);
}
});
If you use .ajax instead of .post you can include traditional: true

Categories

Resources