简体   繁体   中英

Posting AJAX string to MVC Controller

I am trying to post a string (the name of the href the user clicked on) using AJAX to my MVC controller (which it will then use to filter my table results according to the string).

Whilst I have managed to get it to post (at-least according to the alerts) on the AJAX side, it doesn't seem to arrive properly on the controller side and is seen as null in my quick error capture (the if statement).

Please excuse the useless naming conventions for the moment. I've been going through countless methods to try and fix this, so will name properly when I've got a proper solution :).

I've been at work for this for a long while now and can't seem to solve the conundrum so any help is appreciated please! I'm very new to AJAX and MVC in general so I'm hoping it's a minor mistake. :) (FYI I have tried both post and get and both seem to yield the same result?)

Controller:

[Authorize]
    [HttpGet]
    public ActionResult GetSafeItems(string yarp)
    {
        using (CBREntities2 dc = new CBREntities2())
        {
            if (yarp == null)
            {
                ViewBag.safeselected = yarp;
            }
            var safeItem = dc.Items.Where(a => a.Safe_ID == yarp).Select(s => new {
                Serial_Number = s.Serial_Number,
                Safe_ID = s.Safe_ID,
                Date_of_Entry = s.Date_of_Entry,
                Title_subject = s.Title_subject,
                Document_Type = s.Document_Type,
                Sender_of_Originator = s.Sender_of_Originator,
                Reference_Number = s.Reference_Number,
                Protective_Marking = s.Protective_Marking,
                Number_recieved_produced = s.Number_recieved_produced,
                copy_number = s.copy_number,
                Status = s.Status,
                Same_day_Loan = s.Same_day_Loan
            }).ToList();

        //    var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
            return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
        }
    }

AJAX function (on View page):

$('.tablecontainer').on('click', 'a.safeLink', function (e) {
            e.preventDefault();
            var yarp = $(this).attr('safesel');
            var selectedSafeZZ = JSON.stringify("SEC-1000");
            $.ajax({
                url: '/Home/GetSafeItems',
                data: { 'yarp': JSON.stringify(yarp) },
                type: "GET",
                success: function (data) {
                    alert(yarp);
                    console.log("We WIN " + data)
                },
                error: function (xhr) {
                    alert("Boohooo");
                }
            });

        })

** The Alert reveals the correct type: "SEC-1000" But the console Log shows: WE WIN [Object object]??

I have tried something basic in a new mvc dummy project :

View page basic textbox and a button :

<input type="text" id="txt_test" value="test"/>
<button type="button" class="btn" onclick="test()">Test</button>

<script type="text/javascript">
        function test()
        {
            var text = $("#txt_test")[0].value;

            $.ajax({
            url: '@Url.RouteUrl(new{ action="GetSafeItems", controller="Home"})',
            // edit 
            // data: {yarp: JSON.stringify(text)},
            data: {yarp: text},
            type: 'GET',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function(data) {
                // edit 
                // alert(JSON.stringify(data));
                alert(data.data);
            }});
        }           
</script>

Controller :

[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
        return Json(new {data = string.Format("Back end return : {0}",yarp)}
        , JsonRequestBehavior.AllowGet);
}

Alert result => {"data":"Back end return : \\"test\\""}

It's a simple ajax call to a web method. You don't return a view, so I don't understand the use of

if (yarp == null)
{
    ViewBag.safeselected = yarp;
}

Also I see an [Authorize] attribute, you perhaps use some authentication and I don't see any authentication header on your ajax call

尝试这个:

$.each(data, function (i) { console.log("We WIN " + data[i].Serial_Number )});

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