Я новичок в веб-программировании.Я начал с учебного проекта ASP.NET
, сделал html-страницу и выполнил все MVC
.Теперь в моем коде C#
есть массив, который я хотел бы передать функции javascript
.Но я не знаю, как и я не могу найти что-либо в Интернете.
Возможно ли это, и если да, то как мне это сделать?
Обновление
Итак, я пробую ниже на основе первоначальной обратной связи.Мой проект .netcore2, поэтому я не могу использовать материал System.web.Я прочитал в Интернете, что json.NET позволяет мне выполнять сериализацию / десериализацию, поэтому я использую это вместо этого.
2-е обновление
Я обновил DeserializeObject для использования словаря, но все еще получаю то же неопределенное исключение.
Уточнение:
На стороне клиента я думаю, что приведенный ниже код вызывает исключение всплывающего окна.Таким образом, ответ не выполняется на стороне C # / MVC / Controller ... Я просто не понял, как решить эту проблему ...
if (response.Status !== "OK") {
alert("Exception: " + response.Status + " | " + response.Message);
Клиент
<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 / Контроллер
[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;
}