1

I have a simple function that searches for item I want in my database and retrieves it in my controller.

[HttpPost]
public ActionResult Index(string searchString)
{
    var user = from m in db.Users select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        user = user.Where(s => s.UserName.Contains(searchString));
    }

    return View(user);
}

And then in my Javascript I send a value to search:

$('#test').click(function(e) {
    e.preventDefault();

    var user = "John";

    $.ajax({
        url: "@Url.Action("Index", "Users")",
        data { "searchString": user },
        type: "post",
        success: function (saveResult) {
            console.log(saveResult);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr, ajaxOptions, thrownError);
        }
    })
})

However of course all this does it return my view inside the console window which is something like: enter image description here

But I would like to return a json object I can use.

2 Answers 2

2

just use the Json Action method.

return Json(user);

Edit:

As a side note, I would also set my return Type to be JsonResult for clarity

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

3 Comments

Perfect! Is there a way to change the name of the json object that comes back? It came back as Array[1].
I'm assuming Array[1] is the content displayed from the console.log(saveResult) call. If so, that's really just the description of what is stored in the saveResult. Your code is returning an IEnumerable<User> which is serialized to be an Array of objects in JS. Does that make sense?
Yeah I get it now, either way it saved me so thank you.
1

You just return as JsonResult such as below:

 public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}

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.