简体   繁体   中英

How to pass an object to a MVC controller via Jquery Ajax Get

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");
    }
}

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.

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);    
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM