C# MVC pass parameters from View to Controller using dotnetfiddle

I am learning C# MVC using dotnetfiddle web to write code.
I have created a new project with the default code of dotnetfiddle for MVC type, but I want to display the question in the alert instead of the answer.

I want to know how to pass parameters to the controller from the view.

This is the ajax method:

$.ajax({
    url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
    data: JSON.stringify({Answer: '', Question: $('#Question').val()}),
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(resp) {
        openAlert(resp.result);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
            openAlert("ERROR: " + errorThrown); 
    }
});

And this is the controller method:

[HttpPost]
public JsonResult GetAnswer(string question)
{               
    int index = _rnd.Next(_db.Count);
    var answer = _db[index];
    return Json(new { result = question});
}

You can check and test the code here: dotnetfiddle (Edit: it will be a good answer if it works here)

here is solutions:

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Solution 1

You are getting the value of the question in the action because your action has got a single parameter string question in there.

What you need to do is:

  1. Send a json object from the view
  2. In the action user a model with two properties (Answer and Question) to get the value sent by the view
  3. Then in the action you decide what data you need to send to view

View:
Send JSON object to action:

JSON.stringify({Answer: '', Question: $('#Question').val()})

When you get the data returned from controller:

openAlert(resp.Answer);

Controller:

public JsonResult GetAnswer(MyQA model)
{
    // model.Answer
    // model.Question
    // Your business logic goes here

    return Json(new { result = model});
}

Here is the MyQA class:

public class MyQA
{
    public string Answer { get; set; }
    public string Question{ get; set; }
}

Solution 2

dotnetfiddle had a problem with this line: contentType: "application/json; charset=utf-8",

change script to :

$('.submit').click(function() {
  if ($('form').valid()) {
    $.ajax({
      url: '@Url.Action("GetAnswer", "Home")',
      data: {
        Answer: '',
        Question: $('#Question').val()
      },
      type: 'POST',
      dataType: 'json',
      success: function(resp) {
        openAlert('Answer :' + resp.Answer + ' -----Question : ' + resp.Question);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        openAlert("ERROR: " + textStatus);
      }
    });
  } else {
    closeAlert();
  }
});

change action GetAnswer to :

[HttpPost]
public JsonResult GetAnswer(string Answer,string Question)
{               
   int index = _rnd.Next(_db.Count);
     var answer = _db[index];
     return Json(new {Answer = answer,Question = Question});
}

Solution 3

These code changes will work for you. If you wanna verify check the fiddle. DotNetFiddle

Client side Changes

                $.ajax({
                    url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
                    data: {"Answer": '', "Question": $('#Question').val()},
                        type: 'POST',
                        success: function(resp) {
                            openAlert(resp.Question);
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) { 
                            openAlert("ERROR: " + errorThrown); 
                        }
                    });

Server Side Changes

[HttpPost]
        public JsonResult GetAnswer(SampleViewModel model)
        {               
            int index = _rnd.Next(_db.Count);
            var answer = _db[index];
            return Json(model);
        }

Solution 4

This is the method I used to pass parameters to controller

First, assign the parameter you want to pass to a variable with the value from the
input id as stated in your dotnetfiddle

var questionParam = $("#Question").val();

Then for passing it to AJAX, I think your method is already correct, this is how I do it

$.ajax({
    url: '/Home/GetAnswer?question=' + questionParam ,
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(resp) {
        openAlert(resp.result);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
            openAlert("ERROR: " + errorThrown); 
    }
});

This method works for me in my project, if the value is a string I think you don’t need to stringify the value.

I’m still a beginner as well so maybe my method is wrong or not the best way to do it, I hope it helps you.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply