Home > Software engineering >  ASP.NET Core pass data from AJAX to View
ASP.NET Core pass data from AJAX to View

Time:04-09

I am new to ASP.NET and I am trying to pass a JSON object via AJAX to a view where the object can be modified. I have a button with a click event that uses a POST method to send the data to an Action method that deserializes the string into an object and redirects that object to another Action method that renders the View. The AJAX success function completes successfully and I can see the View in the Network tab of Developer Tools but in the UI the button appears to be doing nothing at all. I am not familiar with routing in ASP.NET and am wondering if there is a routing issue in my Controller.

AJAX

function myFunc(){
     
    $("#myTable").unbind().on('click','.stageBtn',function(){
     // get the current row
     var currentRow = $(this).closest("tr")[0]; 
     var cells = currentRow.cells;

    var dataObject = JSON.stringify({
    'serial': cells[2].textContent,
    'sku': cells[3].textContent,
    'make': cells[0].textContent,
    'model': cells[1].textContent,
    'quantity': cells[4].textContent,
    'description': cells[5].textContent,
    'location': cells[6].textContent,

        });

        $.ajax({
    type: "POST",
    url: 'Home/Stage',
    contentType: 'application/json',
    data: JSON.stringify(dataObject),
    success:function() {
       alert("Success");
    },
    error: function () {
        alert("Fail");
    }
});
   
     event.stopPropagation? event.stopPropagation() : event.cancelBubble = true;
     return false;
    });
   
    return false;
 }

Controller

[HttpPost]
        public IActionResult Stage([FromBody]string p) {

            Product product = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(p);
            if (!ModelState.IsValid)
            {
                return BadRequest("Enter required fields.");
            }
            else {
                return RedirectToAction("Detail",product.ToStaging());
            }
           
        }

       
        public IActionResult Detail(Staging s)
        {
            return View(s);
        }

The Request URL is of the format: localhost/Home/Detail?{serial}&{sku}&{make}&{model}&{quantity}&{description}

CodePudding user response:

Okay, so you are using AJAX which is used to update a portion of the page without reloading the entire page or do a redirection based on the result that you get back from your server.

Now, you are trying to redirect from the Controller itself which is incorrect because that is not how AJAX works. You would need to send back a result to you View from your AJAX call and then do the redirection

In your case, you can do this:

You need to return a JSON result from your Controller. Now since you want to also send your Model, you can store it in a Session variable and access it after the redirect from the AJAX call:

[HttpPost]
public IActionResult Stage([FromBody]string p) 
{

    Product product = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(p);
    if (!ModelState.IsValid)
    {
         return Json(new {status="false", msg= "Enter required fields."});
    }
    else {
        Session["myModel"] = product.ToStaging();
        return Json(new {status="true", msg= "Redirect now"});
    }      
}

And your AJAX call will be:

$.ajax({
    type: "POST",
    //url: 'Home/Stage',
    url: '@Url.Action("Stage", "Home")',
    contentType: 'application/json',
    data: JSON.stringify(dataObject),
    success:function(data) {
      if(data.status=="true")
      {
        var urlToRedirect= '@Url.Action("Detail","Home")';
        window.location.href = urlToRedirect; //Redirect here
      }
      else
      {
        alert(data.msg)
      }
    },
    error: function () {
        alert("Fail");
    }
});

And you can retrieve your Model in your Detail method like this:

public IActionResult Detail()
{
   Staging myModel = new Staging();
   if(Session["myModel"] != null)
   {
      //Cast your session variable as required
      myModel  = (Staging)(Session["myModel"]);
   }
   return View(myModel);
}
  • Related