Category Archives: Jquery

Jquery

pass model from View to Controller via AJAX – tried everything

Hello guys, 

I have tried everything trying to pass a model (from a strongly typed view) to a controller action using ajax and it always arrives empty, here is my code, please tell me what’s wrong with it (i have tried a variety of things tho and stll nothing has worked):

the model i am trying to pass is a ViewModel like this: (is the [Serializable] mandatory ?)

 [Serializable]
    public class RatingAreaViewModel
    {
        public int userId {get; set;}

        public double[] currentRating {get; set;}
        public double[] newUserRating { get; set; }

        public bool hasAlreadyVoted { get; set; }
        public double[] oldUserRating { get; set; }
        
        public int numberOfVotes { get; set; }

        public RatingAreaViewModel()
        {
            currentRating = new double[5] { 0, 0, 0, 0, 0 };
            newUserRating = new double[5] { 0, 0, 0, 0, 0 };
            oldUserRating = new double[5] { 0, 0, 0, 0, 0 };
        }

    }

and here is the ajax function in my view: 

  var obj = @Html.Raw(Model);
     
        function submitRating() {

            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }
    

I have tried soo many combinations including JSON.Stringify and still the problem is that the model arrives empty at the controller (all zero values)

public ActionResult RatePlayer(RatingAreaViewModel ravm, int vote1,int vote2,int vote3,int vote4)
{

    // AT THIS POINT HERE ALL VOTES ARRIVE OK BUT THE MODEL ARRIVES EMPTY
    
return partialview(...); }

thank you a lot guys!!

try…

var obj = @Html.Raw(Json.Encode(Model));

// and then change the 'data' option to:

data: JSON.stringify({ "ravm": obj, "vote1": vote1, "vote2": vote2, ... }),
...

You need to stringify your JSON data

First refer the reply of John

also try this

aymane07

data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

data: { ravm: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

Pass your data like this in jquery ajax call.

data: $(‘#formName’).serialize() + "&vote1=" + vote1+ "&vote2=" + vote2

Hi aymane07,

Based on my test, to serialize the object to JSON string, we should to use
JavaScriptSerializer
class.

For your requirement, you need add the object to a JSON, then convert it to the JSON string.

Please refer to this code below to achieve your requirement:

 public class Field
    {
        [Required]
        public string DataInfo { get; set; }

        [Required]
        public string Value { get; set; }

        //[MustBeTrue(ErrorMessage="required")]
        public bool IsRequired { get; set; }

        [Required]
        public int serverIDTo { get; set; }

    }
 public ActionResult JqueryFormSubmit()
        {
            Field f=new Field(){ DataInfo="dataInfor1", IsRequired=true, serverIDTo=2, Value="value1" };
            return View(f);
        }
        [HttpPost]
        public string JqueryFormSubmit(Field f, string txtQues,FormCollection c)
        {
            string str = txtQues ?? "empty";
            if (f != null && !string.IsNullOrEmpty(f.DataInfo))
                str += f.DataInfo;
            else
                str += " and null";
            return str;    
        }
@model MvcDemo2.Models.Field

@{
    ViewBag.Title = "JqueryFormSubmit";
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string objJson=serializer.Serialize(Model);
}
 $(document).ready(function () {
            $('#btnSubmit').click(function () {
                var obj =JSON.parse('@Html.Raw(objJson)'); 
                var jsonData =JSON.parse(JSON.stringify({ f: {}, txtQues: "gg" }));
                //add object to json 
                jsonData.f = obj;
                 $.ajax({
                    url: '@Url.Action("JqueryFormSubmit")',
                    type: 'POST',
                    contentType:"application/json",
                    data: JSON.stringify(jsonData), 
                    success: function (data) {
                        //debugger;
                        alert(data);
                    },
                    error: function (response, xhr, data) {
                      }
                }
            )
            });
});

Best Regards

Starain Chen

What is this; formName ?? I think i don’t have any form in my View

Hello, 

I have tried your exact same code and it doesn’t work! all the votes are passed safely but the object is all zeros and falses :(:(:(

Is there something more basic i am missing…  here the code i tried exactly: 

[httppost] 
public ActionResult RatePlayer(RatingAreaViewModel ravm, int vote1,int vote2,int vote3,int vote4) { }

function submitRating() {

            var obj = JSON.parse('@Html.Raw(objJson)');
            var jsonData = JSON.parse(JSON.stringify({ f: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.f = obj;
            
            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify(jsonData),
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }


@{
    var url = Request.Url.AbsolutePath;
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string objJson = serializer.Serialize(Model);   
}


Please tell me i am missing something i am getting really crazy here :(:(

thanks a lot

Hello

JohnLocke

try…

var obj = @Html.Raw(Json.Encode(Model));

// and then change the 'data' option to:

data: JSON.stringify({ "ravm": obj, "vote1": vote1, "vote2": vote2, ... }),
...

You need to stringify your JSON data

Hello John, I have tried your code and it doesn’t work.. It doesn’t even compile at my end when I write this: 

var obj = @Html.Raw(Json.Encode(Model));

I have this error: IHTMLString returns markup that is not HTML…

cnuonline

First refer the reply of John

also try this

aymane07

data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

data: { ravm: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

Hello, I have tried your code and it doesn’t work.. can’t even get to the controller this way.. plz help

Hi aymane07,

For my code is just a sample. You need modify it.

Based on your code, a parameter name of your action (RatingAreaViewModel) is
ravm, so you need replace f to ravm.

 var jsonData = JSON.parse(JSON.stringify({ ravm: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.ravm = obj;
            

Best Regards

Starain Chen

Starain chen – MSFT

Hi aymane07,

For my code is just a sample. You need modify it.

Based on your code, a parameter name of your action (RatingAreaViewModel) is
ravm, so you need replace f to ravm.

 var jsonData = JSON.parse(JSON.stringify({ ravm: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.ravm = obj;
            

Best Regards

Starain Chen

Thanks for your reply.. I have done exactly what you asked, and it still doesn’t work :)

I have noticed an issue with my code, when i use ravm: {} the request doesn’t even get to the controller action, whereas when i do
object:{} the request gets to the controller action but the object is all zeros. 

Second thing i have noticed is a difference between our code, i am NOT using any form, so when you are saying url: Url.Action (form) i can’t say that, i just write the URL as a string (i don’t think this is causing the problem however).

Also, do you think i should be putting [Serializable] before my class definition of the object or not ? 

below is the working code that gets to the controller but with an emtpy project.. if you have anything else i can try please let me know.. 

thanks a lot!

function submitRating() {

            //var obj = 'Html.Raw(val)';

            var obj = JSON.parse('@Html.Raw(objJson)');
            var jsonData = JSON.parse(JSON.stringify({ object: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));


            jsonData.object = obj;

            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify(jsonData),
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }


I gave up for now and just passed an int Id instead of the object and reconstructed the object back in the controller: I did it this way: 

 $.post(url, { userId: id, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }, function (ratingAreaViewResult) {
                
                $('#ratingArea').html(ratingAreaViewResult);
            });

 BTW, when I pass only the object using this code, it works fine, but as soon as I add the integers the object fails to pass correctly:: there is some big elephant i am missing here!!

if you guys think of something please let me know::

thanks again

Hi aymane07,

aymane07

Second thing i have noticed is a difference between our code, i am NOT using any form, so when you are saying url: Url.Action (form) i can’t say that, i just write the URL as a string (i don’t think this is causing the problem however).

This code is used to generate the URL, the string of JqueryFormSubmit is just the action name. I am not using any form too.

aymane07

Also, do you think i should be putting [Serializable] before my class definition of the object or not ? 

If you are just using JavaScriptSerialize, you don’t need add Serializable attribute to the model class.

Please use the developer tool to check the send data.

On the other hand, please share your project on the OneDrive, we will check it.

Best Regards

Starain Chen

[RESOLVED]edit.cshtml(scaffold), validate database field to accept only 3 value

Hi!

In edit.cshtml(scaffold) I have field1(from database):

<div
class="editor-field">

            @Html.EditorFor(model => model.field1)

            @Html.ValidationMessageFor(model => model.field1)   

</div>

       

    How can I   validate field1(string type)

     to accept only 3  value  ( ex: value1, value2, value3) ?

  Thanks!

Did you meant that comma separted value in a text box?

Hi fvi,

For this requirement, you could use RegularExpressionAttribute class or custom validation.

More information, please refer to:

# RegularExpressionAttribute Class

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute(v=vs.110).aspx

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

Best Regards

Starain Chen

[RESOLVED]Need help to create Cascading DropDownList using MVC4 – C# from Database

I have 2 dropdown lists  (State and City) in my form and I want to show them as Cascading DropDownList.

When I select a State then I want to display only the related cities in that state.

My mode:

public class AustraliaStates
    {
        [Key]
        public string AustraliaStateId { get; set; }
        public string AustraliaStateName { get; set; }
    }

    public class AustraliaCities
    {
        [Key]
        public string AustraliaCityId { get; set; }
        public string AustraliaCityName { get; set; }
    }



    public class Accommodation
    {
        [Key]
        public string A_Unique_Id { get; set; }

        [Display(Name = "Street")]
        public string Street { get; set; }

        [Required]
        [Display(Name = "Suburb")]
        public string Suburb { get; set; }

        [Display(Name = "City")]
        public string City { get; set; }

        [Display(Name = "State")]
        public string State { get; set; }

        public string SelectedAustraliaStateId { get; set; }
        public IEnumerable<SelectListItem> AustraliaStates { get; set; }


        public string SelectedAustraliaCityId { get; set; }
        public IEnumerable<SelectListItem> AustraliaCities { get; set; }
    }

Create.cshtml Get controller:

// GET: /Accommodation/Create
        [Authorize]
        public ActionResult Create()
        {

            var model = new Accommodation
            {
                AustraliaStates = db.AustraliaStates
                             .ToList() // this will fire a query, basically SELECT * FROM Products
                             .Select(x => new SelectListItem
                             {
                                 Text = x.AustraliaStateName,
                                 Value = x.AustraliaStateId
                             }),

                AustraliaCities = db.AustraliaCities
                             .ToList() // this will fire a query, basically SELECT * FROM Products
                             .Select(x => new SelectListItem
                             {
                                 Text = x.AustraliaCityName,
                                 Value = x.AustraliaCityId
                             });
                


            return View(model);
        }

Create.cshtml View

<td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    @Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates, new {@class="DropDownFieldStyle" })

                                </div>
                            </td>    
                        </tr>

                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.City)
                                </div>
                            </td>
                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    : @Html.DropDownListFor(model => model.SelectedAustraliaCityId, Model.AustraliaCities, new {@class="DropDownFieldStyle" })
                                </div>
                            </td>    
                        </tr>

I need to solution to show the DDL as Cascading DropDownList.

can someone please help me?

Thanks in advance.

Here is the form I am working on:

http://overseasindians.com.au/Accommodation/Create

Typical cascading dropdown lists only load the first list initially.  So in your case, you would load your States to the view.  Upon selecting a state, a JSON get-request is made back to your controller, where you’ll return a list of cities based on the
selected state.  Your Cities dropdown will also be hidden at the start, but will be revealed once a country is selected.  Also, you don’t want to return a model based on your two lists because a Create view needs to reserve a model specifically for the form
elements of the View.

public ActionResult Create()
{
  var states = db.Australiastates.ToList();

  ViewBag.stateList = states;

  return View();
}

In the above action, we create a list of States and pass them to the view as a ViewBag object.  We do NOT return any model to the view.

Now we create the View:

@model AppName.Models.YourFormModel

@section scripts {
  <script type="text/javascript">
    $("#Cities").hide();

    $("#States").on("change", function () {

// make the get-request
$.getJSON('@Url.Action("GetCities")', { id: $(this).val() }, function (cities) {

// populate the Cities dropdown with returned data
$.each(cities, function (i, city) {
$("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
});

});

// show the Cities dropdown
$("#Cities").show();

}); </script> } <div> @Html.DropDownList("States", new SelectList(ViewBag.stateList, "AustraliaStateId", "AustraliaStateName"), "Select a state") </div> <div> <select id="Cities" /> </div>

In the above view, we have a dropdown list for both States and Cities, however you’ll notice that the Cities dropdown list is just a generic <select> element.  This is because we didn’t initially pass any data from the Create action to the view, so there’s
no reason to have the DropDownList helper.  We also have a "scripts-section" at the top, with a <script> block and some code inside.  The code is jQuery.  the first line hides our Cities dropdown because it will initially be empty, so it doesn’t need to be
shown immediately.  The 2nd part of the script is an on-change event for the States dropdown list.  On-change, we make a call to an action named "GetCities" where we pass an "id" param of the states dropdown value.  The action will use this param to find all
cities associated with the ID and return it back to the View.  Once the data is returned, we populate the Cities dropdown list, and then show the dropdown list so it can be visible.

Next, we need to add the "GetCities" action to take the State ID and return a list of Cities:

[HttpGet]
public ActionResult GetCities(int id)
{
  var cities = db.AustraliaCities.Where(c => c.State_ID == id).ToList();

  return Json(cities, JsonRequestBehavior.AllowGet);
}

This action should be fairly obvious.  We used the state’s ID to gather a list of cities.  The only issue I had with this is that I didn’t see a "StateID" property in your AustraliaCities model, though I feel there should be one to create an association
between City and State.  I’ll let you determine how to use the state’s ID in the action to populate your Cities list.  In any case, once you have your list of cities, you return it as a JSON result.

That’s all there is to it.  This is a complete working solution.  Please let me know if you have questions.

Hi athelli_,

Thanks for your post.

athelli_reddy

Need help to create Cascading DropDownList using MVC4 – C# from Database

You can use JQuery, Please refer to this link:

#Creating cascading dropdownlists using MVC 4 And JQuery

http://jnye.co/Posts/12/creating-cascading-dropdownlists-using-mvc-4-and-jquery

Hope this can be helpful.

Best Regards,

Eileen

Thank you very much John for detailed explanation & your solution is working.

Can you please let me know how can I make State Dropdown menu field as a Mandatory field and show a client side validation if when the dropdown contains "Select a state" value.

public class AustraliaStates
    {
        [Key]
        public string AustraliaStateId { get; set; }
        
        [Required]  ->what else I can add here to make it as a Mandatory if there is "Select a state" value
        public string AustraliaStateName { get; set; }
    }

or do I need to write any java script??

[RESOLVED]how can i use url.action in @helper method ?

Hi dear ,

 I create a @helper method and use @Url.Action helper in it.(in App_Code Folder)

@helper GetNews(int CategoryID, int Rows)
{
         <div class="@Style" id="@CategoryID">
         
                  <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
                                &nbsp;
                                <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
                             </div>
                        
}

after run i get an error :

Compilation Error 
  Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

 Compiler Error Message: CS0103: The name 'Url' does not exist in the current context

Source Error:


 

Line 193:                                </table>*@
Line 194:
Line 195:                                <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
Line 196:                                &nbsp;
Line 197:                                <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
 

Also,
I had
to have
a class named ExtensionMethodHelper
for create external helpers and use it ( in Model folder ).but i
can not call
this
external helpers on the page(.cshtml) that
I’ve created
in
App_Code folder.

in fact after write @Html.  i dont find my favorite external helper (in ExtensionMethod class in Model folder).

for e.g : Html.PersianDate made in ExtensionMethodHelper in Model Folder

   <span class="date">@Html.ToPersianDate(item.DateToShow)</span>

in :

below helper create in App_Code

@helper GetNews(int CategoryID, int Rows)
{
       <div class="@Style" id="@CategoryID">
                <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
                       &nbsp;
                   <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
       </div>
                        
}

 how can i solve it

please help me

thanks

I use the "UrlHelper" class to do this.  Here’s a helper I always used in my projects (prior to bundles).  Use it as an example to expand on your own:

// file name is "Content.cs" stored in App_Code folder

@using System.Web.Mvc; @helper Script(string scriptName, UrlHelper url) { <script type="text/javascript" src="@url.Content("~/Scripts/" + scriptName)"></script> }

the helper in my View then looks like:

@Content.Script("jquery-1.10.1.min.js", Url)

You can see that I pass the "Url" to the helper.  Your helper would then look like…

@helper GetNews(int CategoryID, int Rows, UrlHelper url)
{
  ...

  <a href="@url.Action("Rss", "Home", ...)">

  ...
}

the "url" is lowercase fyi.  Don’t confuse it with Url

[RESOLVED]date formt isue c# and jquery

hello, I have a db with the  data attribute

and i’m using jquery date picker to insert date

in my computer I have no problem choosing and inserting but all users has report error: must be a date format

How can I fix it and what  wrong here ? 

code

in my class :

[DisplayFormat(DataFormatString = "{0:dd MMM }")]
           
public DateTime WeekFrom { get; set; }
        
[DisplayFormat(DataFormatString = "{0:dd MMM }")]

public DateTime? Until { get; set; }
 in my script 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

my Sql look like this 
WeekForm (datetime not null)
Until(datetimee,null)

how  can I fix it and what is wrong  here?

Based on the current format you are using, you’ll likely need to change the format of your DatePicker to match :

$(".date-picker").datepicker({ dateFormat: 'dd MM' });

Additionally, another problem is that the ‘mm’ value you are using in your DateFormat actually denotes minutes instead of months. If you wanted to use months (which is likely), you’ll instead want to use the capitalized ‘MM’ instead :

$(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });

This should help to ensure that the formats coincide between your actual DisplayFormat attributes and the value contained in your DatePicker. Additionally, if you are using Chrome or the jQuery.validate library, you might want to look into
this known issue regarding DateTime objects being parsed or validated improperly.

Rion Williams

Based on the current format you are using, you’ll likely need to change the format of your DatePicker to match :

$(".date-picker").datepicker({ dateFormat: 'dd MM' });

Additionally, another problem is that the ‘mm’ value you are using in your DateFormat actually denotes minutes instead of months. If you wanted to use months (which is likely), you’ll instead want to use the capitalized ‘MM’ instead :

$(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });

This should help to ensure that the formats coincide between your actual DisplayFormat attributes and the value contained in your DatePicker. Additionally, if you are using Chrome or the jQuery.validate library, you might want to look into
this known issue regarding DateTime objects being parsed or validated improperly.

hello Rion, thanks,

using :

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });
})
i'm getting in my page a date that look like this :"30-September-2014" and error MSG :" The field must be a date"

Oops. 

I appeared to get my ASP.NET and jQuery code mixed up. The lowercase format should be fine : 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

Is there any chance that you are using any kind of validation-based scripts (like jQuery.validate)? Or is the error message you are receiving coming from the actual server-side code?

A

Rion Williams

Oops. 

I appeared to get my ASP.NET and jQuery code mixed up. The lowercase format should be fine : 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

Is there any chance that you are using any kind of validation-based scripts (like jQuery.validate)? Or is the error message you are receiving coming from the actual server-side code?

thanks Rion for your time and help.  ,

it look fine on my side . i’ll check with users  to find out.

Problem fix . thanks Rion.

and yes this is Jquery validator.

[RESOLVED]Convert ajax call into chunked calls of 100 for a URL

Excuse me here, I’m rather new to this, so please bear with me.

I have been given the task as stated in the subject, to break the ajax call into chunks of 100.  This is being done as to not run out of URL space.  My instinct (which is probably wrong) is to pass it through as an array.  This is where I’m hitting a wall.
 Here is a chunk of code in the index of Views.

$(document).ready(function() {
var imageNos = ‘@Model.ImageNos’;
var array = imageNos.split(‘,’);

var oTable = $(‘#imageTable’).dataTable(
{
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "ImageData/GetList",
"bLengthChange": false,
"bFilter": false,
"bSort": false,
"bJQueryUI": true,
"aoColumns": [
{ "bSortable": false, "bSearchable": false },
null,
null,
null,
null,
null,
null,
null
],
"fnServerData": function(sSource, aoData, fnCallback) {
aoData.push({ "name": "ImageNos", "value": array });
$.getJSON(sSource, aoData, function(json) {
fnCallback(json)
});
},
"fnRowCallback":function(nRow, aaData) {
var imageno = aaData[1];
$.get("ImageData/ImageDetails?imageNo=" + imageno, function (details) {
oTable.fnOpen(nRow, details, ‘details’);
});
return nRow;
}
});

here is how I;m trying to pass it through to the controller.

public ActionResult GetList(string[] value)
{
var imageNos = new List<long>();
try
{
if (!string.IsNullOrEmpty(value))
{
/*var imgs = ImageNos.TrimEnd(‘,’).Split(‘,’).ToList();
imageNos.AddRange(imgs.Select(i => Convert.ToInt64(i)));*/
}

long totalImages;
var images = ImageRepository.GetSelectedImages(imageNos);
var imageDataModels = images as IList<ImageDataModel> ?? images.ToList();
return Json(new
{
iTotalRecords = imageDataModels.Count,
iTotalDisplayRecords = imageDataModels.Count,
aaData = imageDataModels.Select(x => new[]
{…………

As it is now, I’m getting errors

Error 1 The best overloaded method match for ‘string.IsNullOrEmpty(string)’ has some invalid arguments and 

Error 2 Argument 1: cannot convert from ‘string[]’ to ‘string’ 

I know this is a lot of code, and i’m not even sure I have posted anything that could help someone assist me, but any help on this would be greatly appreciated; I’m feeling a bit overwhelmed and underwater.

edit: I meant to say beforehand that everything works fine before I try the array above, before I split it in the index

I can’t really follow what the code is doing, but you’re getting that error as

string.IsNullOrEmpty(value)

in the above "value" is an array, and IsNullOrEmpty works on strings, not arrays of strings.  If you want to check if an array isn’t empty try

if (value != null && value.Length >0)

Not saying that’s going to fix your issue, but it will get your code to compiled.  Also if you’re worried about "running out of url space" then just POST your data rather than using GET and you don’t need to worry.

Getting data of json array

I create an array with javascript that has some ids. I pass them back to my controller like so

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

What I’m not sure on is how I get that data in my c# code to work with it. Here’s my function in my controller

//how do I get the array passed in as an argument
        [HttpGet]
        public JsonResult GetChildKeys(object var)
        {
            //need to figure out how to read id data and then pass back child keys
            return Json("foobar", JsonRequestBehavior.AllowGet);
        }

The param you choose for your ‘data’ option in the ajax-request must match the param of your post-action. 

[HttpGet]
public JsonResult GetChildKeys(someType ids)
{
...

Is nodeKeys a list of objects, or a string?  That will determine the "someType" above

I knew I’d have to get the type, I just wasn’t for sure what type it would be.

nodeKeys is just a javascript string array;

Something like 

var nodeKeys = ["cat_1", "cat_2", "cat_3"];

That’s not json, but anyway, try

string[] ids

or

List<string> ids

Then you could do

[HttpGet]
public JsonResult GetChildKeys(string[] ids)
{
foreach (var id in ids)
{
// process each id here
}

...
}

I was under the impression if I sent the data like this (underlined in bold)

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

that it would convert that to json for me?

The "data" node will be json, but the data you are passing in the "ids" property is just a plain javascript array.

hi,

usually ajax communication more serialized content, while receiving  action method have to serialise as per mention data type, 

client : var array1 = ["A", "B", "C", "D"];
server : public JsonResult AjaxCallTest(List<string> postedModel){ //code…… }

client : var array = [1, 2, 3, 4, 5];
server : public JsonResult AjaxCallTest(List<string> postedModel){ //code….. }

or just pass json string, then in controller action have to parse posted json to respective model object.

Ref : serializing and deserializing json in c#

Thanks,

Jai

So how do I go about passing that array back to my application?

Basically, there’s some code that runs through a treeview and pulls the ids of any checked items and pushes them into the array. So, I need to send that array of ids back to my controller as json data. I don’t really care how they get there, array, list,
etc. but I just need to be able to loop through them. Ideas?

hi,

Client :

var selectedItems = [1, 2, 3, 4, 5]; // try to push your selected item.

$.ajax({
url: "/Account/AjaxCallTest/", //your url
traditional: true,
dataType: "json",
type:’post’,
data: { ids : selectedItems },
success:function(data) { 
},
error: function (errorMsg) {
}
});

Server:

[HttpPost]
public JsonResult AjaxCallTest(List<int> ids )
{
// your logic…
}

Thanks,

Jai.

That’s what I tried after your first post with no luck. This is what I have

var nodeKeys = ["cat_1", "cat_2", "cat_3"];

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

C# 

        //how do I get the array passed in as an argument
        [HttpGet]
        public JsonResult GetChildKeys(List<string> ids)
        {
            //ids is still null
            var foo = ids;

            //need to figure out how to read id data and then pass back child keys
            return Json("foobar", JsonRequestBehavior.AllowGet);
        }

http://forums.asp.net/t/1934215.aspx?Using+jQuery+ajax+to+call+asmx+webservice+methods

either add

contentType:
"application/x-www-form-urlencoded; charset=UTF-8",

to your $.ajax call, or try

data: JSON.stringify({ ids: nodeKeys }),

I’ve tried both of those and ids is still null

nodeKeys = ["cat_1", "cat_2", "cat_3"];
$.ajax(
{
url: "/Home/GetChildKeys",
data: JSON.stringify({ ids: nodeKeys }),
dataType: "json",
type: "GET"
}).done(function (result) { });

and even

nodeString = "cat_1,cat_2,cat_3";
$.ajax(
{
url: "/Home/GetChildKeys",
data: "{keys: ‘" + nodeString + "’}",
dataType: "json",
type: "GET"
}).done(function (result) { });

You have to set the correct contentType too so the service knows how to interpret the data you are sending.  As well as the link I posted with all the examples, look at this to see how you can use the browser’s dev tools to see what is being sent and what
the response is.

http://forums.asp.net/t/1982579.aspx?Using+the+browser+s+dev+tools+to+diagnose+ajax+problems+and+other+things+