简体   繁体   中英

How to pass data from a C# to javascript function?

I'm a newbie when it comes to web programming. I started off with the ASP.NET tutorial project and I made a html page and did all the MVC stuff. I now have an array in my C# code that I'd like to pass to a javascript function. But I don't know how and I can't find anything online.

Is this possible and if so how do I go about it?

Update

So I am trying the below based on initial feedback. My project is .netcore2 so I can't use the System.web stuff. I read online that json.NET lets me do the serializing/deserializing so I'm using that instead.

2nd update
I updated the DeserializeObject to use Dictionary, but still getting the same undefined exception.

Clarifying:

On the Client side I think it's the below code that is throwing up the popup exception. So the response is not succeeding on the C#/MVC/Controller side... I just haven't figured out how to resolve this...

 if (response.Status !== "OK") {
                alert("Exception: " + response.Status + " |  " + response.Message); 

Client

<script>
var myRequest = {
    key: 'identifier_here',
    action: 'action_here',
    otherThing: 'other_here'
};

//To send it, you will need to serialize myRequest.  JSON.strigify will do the trick
var requestData = JSON.stringify(myRequest);

$.ajax({
    type: "POST",
    url: "/Home/MyPage",
    data: { inputData: requestData }, //Change inputData to match the argument in your controller method

    success: function (response) {
        if (response.Status !== "OK") {
            alert("Exception: " + response.Status + " |  " + response.Message);
        }
        else {
            var content = response;//hell if I know
            //Add code for successful thing here.
            //response will contain whatever you put in it on the server side.
            //In this example I'm expecting Status, Message, and MyArray

        }
    },
    failure: function (response) {
        alert("Failure: " + response.Status + " |  " + response.Message);
    },
    error: function (response) {
        alert("Error: " + response.Status + " |  " + response.Message);
    }
});

C#/MVC/Controller

    [HttpPost]
    public JsonResult RespondWithData(string inputData)//JSON should contain key, action, otherThing
    {
        JsonResult RetVal = new JsonResult(new object());  //We will use this to pass data back to the client

        try
        {
            var JSONObj = JsonConvert.DeserializeObject<Dictionary<string,string>>(inputData);

            string RequestKey = JSONObj["key"];
            string RequestAction = JSONObj["action"];
            string RequestOtherThing = JSONObj["otherThing"];

            //Use your request information to build your array
            //You didn't specify what kind of array, but it works the same regardless.
            int[] ResponseArray = new int[10];

            for (int i = 0; i < ResponseArray.Length; i++)
                ResponseArray[i] = i;


            //Write out the response
            RetVal = Json(new
            {
                Status = "OK",
                Message = "Response Added",
                MyArray = ResponseArray
            });
        }

        catch (Exception ex)
        {
            //Response if there was an error
            RetVal = Json(new
            {
                Status = "ERROR",
                Message = ex.ToString(),
                MyArray = new int[0]
        });
        }
        return RetVal;
    }

The short answer is that a function on the client can't be called directly from the server. You will need to have the client ask for the information.

JQuery is your easiest path on the client side. Try something like this:

Client Code

   var myRequest = {
        key: 'Put an identifier here',  //Pack myRequest with whatever you need
        action: 'Put an action here',
        otherThing: 'Put other stuff here'
    };

    //To send it, you will need to serialize myRequest.  JSON.strigify will do the trick
    var requestData = JSON.stringify(myRequest);

    $.ajax({
        type: "POST",
        url: "Your URL goes here",
        data: { inputData: requestData }, //Change inputData to match the argument in your controller method

        success: function (response) {
            if (response.Status !== "OK") {
                alert("Exception: " + response.Status + " |  " + response.Message);
            }
            else {
                //Add code for successful thing here.
                //response will contain whatever you put in it on the server side.  
                //In this example I'm expecting Status, Message, and MyArray

            }
        },
        failure: function (response) {
            alert("Failure: " + response.Status + " |  " + response.Message);
        },
        error: function (response) {
            alert("Error: " + response.Status + " |  " + response.Message);
        }
    });

On the server side, you will need to be able to receive the request and send the data back.

C# / MVC / Controller Code

[HttpPost]
public JsonResult YourMethodName(string inputData)//JSON should contain key, action, otherThing
{
    JsonResult RetVal = new JsonResult();  //We will use this to pass data back to the client

    try
    {
        var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(inputData);
        string RequestKey = JSONObj["key"];
        string RequestAction = JSONObj["action"];
        string RequestOtherThing = JSONObj["otherThing"];

        //Use your request information to build your array
        //You didn't specify what kind of array, but it works the same regardless.
        int[] ResponseArray = new int[10];

                //populate array here

        //Write out the response
        RetVal = Json(new
        {
            Status = "OK",
            Message = "Response Added",
            MyArray = ResponseArray
         });
        }

    }
    catch (Exception ex)
    {
        //Response if there was an error
        RetVal = Json(new
        {
            Status = "ERROR",
            Message = ex.ToString(),
            MyArray = new int[0]
        });
    }
    return RetVal;
}

You'll need these namespaces in your controller declaration:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Web.Mvc;

That should get you well on your way. Hope it helps!

What I do,

in c#

protected string arrayElements = String.Join("_separator_",yourArray);

in aspx page

<script>
 var arr = arrayElements;
</script>

and use arr in external js files.

There are a number of ways.

A few of them are directly done in the MVC view. You need to get the c# variable into the view. There are 2 typical ways of doing this: 1) as a model 2) as a ViewBag element

To do it as a model variable, you want to pass the array into the View() function from the controller. eg

 MyClass[]  myArray = new MyClass[] {  new MyClass("A"), new MyClass("B"), ...};
 View(myArray);

in the view you refer to the variable put putting something like this at the top of the view:

 @model  MyClass[]

Later in the view the variable is assigned to the "Model" variable. eg

 @Model[0]  

The other way is to assign it to the ViewBag in the Controller:

 ViewBag.MyArray = myArray;

Then in the view you can access the ViewBag:

@ViewBag.MyArray[0]

So now you need to get it into Javascript. This can be done by translating the variable into javascript code manually (if you want). There are several packages that do a great job of this for you. See Newtonsoft.Json as a common one. Json is just a javascript expression so it can be "evaluated" as javascript by putting it where javascript code would go:

 <script>
      var myJavascriptArray = @Html.Raw(Json.Convert(ViewBag.MyArray));
</script>

Be careful that the array cannot contain any code that could be manipulated by users to do bad things on your page.

As another technique, the javascript can call an api controller that delivers the data in Json format. The asp.net controller will typically do the JSON conversion for you. You use an ajax call from Jquery, or a raw javascript "fetch" call to get the data from the api controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM