Kyle Thompson Kyle Thompson - 1 year ago 34
Ajax Question

ASP.NET MVC Pass a String to a Controller through an AJAX Call

I'm attempting to pass a string as a parameter for a controller in the URL of an AJAX call in a separate view. I want it to have the same nullable functionality as when you pass (int? id) in the controller, but instead be a string. Here's my code:

Separate View:

url: "Save/"+string
}).done(function (data) {
$('body').append('<p>Query was successfully saved to the database.</p>');


public ActionResult Save(string? data)
if(data == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return View(data);

and the view for
has virtually nothing in it, I'm just trying to print the string that was passed.


First, string is a class, so it cannot be nullable, i.e. you don't need ? after parameter type declaration:

public ActionResult Save(string data)

Now in order to access this method you need correct URL. You did not write the name of your controller, so I will assume it is SomeController. Additionally, I assume that you are using default MVC routes, i.e. no custom ones. If these assumptions are valid the URL that you need is:

url: "/some/save/?data=yourvalue"

Let's break it down:

  • some stands for the name of your controller, without a word Controller, so SomeController becomes some in URL.
  • save is the name of your method.
  • data is the name of the parameter in the method. Default routes have parameter id as third segment of URL, but your parameter is called data, so you need to pass it as query string.
  • yourvalue is the value that will be passed to the method.

UPDATE: Another issue that was mentioned in comments, is that statement

return View(data);

is looking for a view which is provided in parameter value. This is expected behavior, because overload of method View with single parameter of type string is trying to render the view, which is passed as parameter.

To fix the issue, you should use overload with 2 parameters and pass the name of the view as first parameter and model as second:

return View("Save", data);