0

I am working on an ASP.NET MVC 4 app. This app has a controller with an action that looks like the following:

public class MyController : System.Web.Http.ApiController
{
  [ResponseType(typeof(IEnumerable<MyItem>))]
  public IHttpActionResult Get(string id, string filter)
  {
    IEnumerable<MyItem> results = MyItem.GetAll();
    List<MyItem> temp = results.ToList<MyItem>();

    var filtered = temp.Where(r => r.Name.Contains(filter);
    return Ok(filtered);
  }
}

I am calling this action using the following JavaScript, which relies on the Select2 library:

$('#mySelect').select2({
  placeholder: 'Search here',
  minimumInputLength: 2,
  ajax: {
    url: '/api/my',
    dataType: 'json',
    quietMillis: 150,
    data: function (term, page) {
      return {
        id: '123',
        filter: term
      };
    },
    results: function (data, page) {
      return { results: data };
    }
  }
});

This code successfully reaches the controller action. However, when I look at id and filter in the watch window, I see the following errors:

The name 'id' does not exist in the current context 
The name 'filter' does not exist in the current context 

What am I doing wrong? How do I call the MVC action from my JavaScript?

Thanks!

1
  • Could you also show your routes please? In addition to David's answer (which sounds right) it could be around that. Commented Sep 26, 2014 at 12:34

1 Answer 1

1

You're not passing actual data as the parameters, you're passing a function:

data: function (term, page) {
  return {
    id: '123',
    filter: term
  };
}

Unless something invokes that function, the result will never be evaluated. Generally one would just pass data by itself:

data: {
  id: '123',
  filter: term
}

If, however, in your code there's a particular reason (not shown in the example) to use a function, you'll want to evaluate that function in order for the resulting value to be set as the data:

data: (function (term, page) {
  return {
    id: '123',
    filter: term
  };
})()

However, these errors also imply a second problem, probably related to however you're trying to debug this:

The name 'id' does not exist in the current context

The name 'filter' does not exist in the current context

Even if no values were being passed, id and filter still exist in the scope of the action method. They may be null or empty strings, but the variables exist. It's not clear where you're seeing that error, but it's definitely not in the scope of the action method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.