0

I am new to jquery and I can't resolve the following problem : I want to pass an object to one of the controllers in my mvc application. Here is what I got so far:

function enterPressed() {
    $(function () {
        $('#textBox').keypress(function (e) {

            var code = e.keyCode ? e.keyCode : e.which;
            if (code == 13) {
                doSomethingElse(textBox.value)

            }
        });
    });
}

function doSomethingElse(p) {
    $.ajax({
        type: 'GET',
        data: {string: p},
        url: '"Control/AddControl/Index"',
        success: function (data) { alert(p) },
        error: function (errorData) { alert("fail") }
    });
    return true;

But every time when I press enter I end up with the fail. My controller is found in ~/Controllers/Control/AddControl. Do any of you see the problem ?

My C# code:

  public class AddControlController : Controller
{
    //
    // GET: /AddControl/


    public ActionResult Index(string control)
    {
        return RedirectToAction("ShowControl");
    }
}
2
  • 1
    your url is /AddControl/Index Commented Jul 11, 2013 at 13:56
  • "I end up with the fail" - that is because you are ignoring the errorData. Do you want us to guess the error? Commented Jul 11, 2013 at 14:00

3 Answers 3

2

You should change value name to control, as action expected. Also you can use @Url.Action() helper for setting url param.

$.ajax({
        type: 'GET',
        data: { control : p},
        url: '@Url.Action("Index","AddControl")',
        success: function (data) { alert(p) },
        error: function (errorData) { alert("fail") }
    });

Finally, your action can't return redirect action with ajax response. If you want to make redirect after successful response, you can make it in client side.

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

Comments

1

There are a few problems:

1-you are using a wrong url. The correct url is '/AddControl/Index'.

2-Your code in your controller won't work, since you are using ajax. You should return Json and handle the redirect in the client side.

3-You should allow GET through ajax:

public ActionResult Index()    
{
   return Json("Ok", JsonRequestBehavior.AllowGet);    
}

Comments

1

You might want to just POST in stead of GET.

function doSomethingElse(p) {
    $.post(
        '@Url.Action("Index", "AddControl")',
        {
            control: p
        },
        function (data) {
            alert(data);
        }
    );
}

You should decorate your controller action with the HttpPost attribute:

[HttpPost]
public ActionResult Index(string control)
{
    return Json("I received this: " + control);
}

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.