locked
Resource cannot be found after Ajax postback RRS feed

  • Question

  • User1941728045 posted

    Hi,

    I have a View which when a row is clicked, it will go to the Controller and call a Partial View. The Partial View, has some information and a text box which is then populated. Once populated, the user would click the button which would then do an Ajax call., The Ajax call is sitting in the View. Below is the code:

          $(document).on('click', '.orange_btn_ask', function () {
             $.ajax({
                type: 'POST',
                url: "/Travel/QueryB",
                data: { reply: $(this).parent().siblings().eq(0).find("textarea").val() },
                success: function (data) {
                   location.reload("/Travel/MyTlBHeaderTR"); }
             });
          });

    The above call would then go to the Controller [Post] method, and execute the procedure, QueryB. Once this is done, im expectingthe return page to be /Travel/MyTlBHeaderTR because it would go to the 'Success' part of the Ajax above.

    The QueryB proceduure is found below which i in my Controller.

            [HttpPost]
            public async Task<ActionResult> QueryB(string reply, string l_frompage)
            {
               string queryBComments;
               Int64 tID;
               DateTime tlBDate;
               Double quoteAmount;
    
               ViewBag.userName = SessionBag.Current.UserName;
               ViewBag.userTypeID = SessionBag.Current.userTypeID;
               TempData["loggedIn"] = SessionBag.Current.loggedIn;
    
               tID = Convert.ToInt64(TempData["tID"].ToString());
               tBDate = Convert.ToDateTime(TempData["tBDate"].ToString());
               quoteAmount = Convert.ToDouble(TempData["quoteAmount"]);
               queryBComments = reply.ToString();
    
               if (SessionBag.Current.UserName == null)
               {
                  TempData["message"] = "Your session has timed out.";
                  SessionBag.Current.loggedIn = "FALSE";
                  TempData["loggedIn"] = SessionBag.Current.loggedIn;
    
                  return PartialView("~/Views/Shared/_SessionExpiredPage.cshtml");
               }
    
               if (tID == 0)
               {
                  ViewBag.Message = "An error occurred. We cannot pickup the ID. Please contact support.";
               }
    
               if (tBDate == null)
               {
                  ViewBag.Message = "An error occurred. We cannot pickup the date. Please contact support.";
               }
    
               if (quoteAmount == 0)
               {
                  ViewBag.Message = "An error occurred. We cannot pickup the amount. Please contact support.";
               }
    
               if (queryBComments == null)
               {
                  ViewBag.Message = "An error occurred. We cannot pickup query you have posted. Please contact support.";
               }
    
               DBController dbcontroller = new DBController();
    
                if (dbcontroller.DBConnection())
                {
                   MySqlCommand command = new MySqlCommand("insert_queryb", dbcontroller.conn);
                   command.CommandType = System.Data.CommandType.StoredProcedure;
    
                   command.Parameters.Add(new MySqlParameter("userName", SessionBag.Current.UserName));
                   command.Parameters["@userName"].Direction = System.Data.ParameterDirection.Input;
    
                   command.Parameters.Add(new MySqlParameter("tID", tID));
                   command.Parameters["@tID"].Direction = System.Data.ParameterDirection.InputOutput;
    
                   command.Parameters.Add(new MySqlParameter("queryBComments", queryBComments));
                   command.Parameters["@queryBComments"].Direction = System.Data.ParameterDirection.Input;
    
                   command.Parameters.Add(new MySqlParameter("tBDate", tBDate));
                   command.Parameters["@tBDate"].Direction = System.Data.ParameterDirection.Input;
    
                   command.Parameters.Add(new MySqlParameter("quoteAmount", quoteAmount));
                   command.Parameters["@quoteAmount"].Direction = System.Data.ParameterDirection.Input;
    
                   command.Parameters.Add(new MySqlParameter("trEmailAddress", MySqlDbType.LongText));
                   command.Parameters["@trEmailAddress"].Direction = System.Data.ParameterDirection.Output;
    
                   command.Parameters.Add(new MySqlParameter("taEmailAddress", MySqlDbType.LongText));
                   command.Parameters["@taEmailAddress"].Direction = System.Data.ParameterDirection.Output;
    
                   try
                   {
                      command.ExecuteNonQuery();
    
                      TempData["tID"] = (Int64)command.Parameters["?tID"].Value;
                      String l_tr_emailAddress = (String)command.Parameters["?trEmailAddress"].Value;
                      String l_ta_emailAddress = (String)command.Parameters["?taEmailAddress"].Value;
    
                      dynamic email1 = new Email("QueryBMail");
    
                      email1.From = "support@bt.com";
                      email1.To = l_ta_emailAddress;
                      email1.tID = TempData["tID"];
                      email1.queryBComments = queryBComments;
    
                      await Task.Run(() => email1.SendAsync());
    
                      dynamic email2 = new Email("QueryBMail");
    
                      email2.From = "support@bt.com";
                      email2.To = l_tr_emailAddress;
                      email2.tID = TempData["tID"];
                      email2.queryBComments = queryBComments;
    
                      await Task.Run(() => email2.SendAsync());
    
                      TempData["frompage"] = "QueryB";
                      dbcontroller.conn.Close();
                   }
    
                   catch (MySql.Data.MySqlClient.MySqlException ex)
                   {
                      dbcontroller.conn.Close();
                      ViewBag.Message = "Could not create query on database. Error " + ex.Number + " has ocurred. Please try again or contact the system administrator";
    
                      return View("_TRError");
                   }
    
                   return View("MyTHeaderTR");
    
                }
                else
                {
                   ViewBag.Message = "Could not connect to the database. Please try again or contact the system administrator";
                   return View("_TRError");
            }
    

    However, i just get "The Resource cannot be found", Http404. It cannot find the link. When i look at the URL, it looks correct.

    Your help is greatly appreciated.

    Ta,

    Naren

    Thursday, October 3, 2019 6:33 PM

Answers

  • User-474980206 posted

    also this is silly code (call ajax, then redirect in javascript):

      $(document).on('click', '.orange_btn_ask', function () {
             $.ajax({
                type: 'POST',
                url: "/Travel/QueryB",
                data: { reply: $(this).parent().siblings().eq(0).find("textarea").val() },
                success: function (data) {
                   location.reload("/Travel/MyTlBHeaderTR"); }
             });
          });
    

    you should just do a form post and redirect. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 3, 2019 7:41 PM

All replies

  • User475983607 posted

    The QueryB action was not found in the Travel controller.   We cannot see the controller so there's not much the forum can do.  Perhaps you forgot to add a [HttpPost] attribute to the QueryB action or the QueryB action is in another controller.

    Thursday, October 3, 2019 6:39 PM
  • User-474980206 posted

    also this is silly code (call ajax, then redirect in javascript):

      $(document).on('click', '.orange_btn_ask', function () {
             $.ajax({
                type: 'POST',
                url: "/Travel/QueryB",
                data: { reply: $(this).parent().siblings().eq(0).find("textarea").val() },
                success: function (data) {
                   location.reload("/Travel/MyTlBHeaderTR"); }
             });
          });
    

    you should just do a form post and redirect. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 3, 2019 7:41 PM
  • User475983607 posted

    You added the code... Anyway, I cannot reproduce the 404.  My test code.

    <h1>Index</h1>
    
    <div class="row">
        <div class="col-md-4">
            <form asp-action="Index">
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" id="submit" />
                </div>
            </form>
        </div>
    </div>
    
    @section scripts{
        <script>
            $('#submit').click(function (e) {
                e.preventDefault();
    
                $.ajax({
                    method: "POST",
                    url: '@Url.Action("QueryB")',
                    data: { reply: "Hello World" },
                    success: function (response) {
                        console.log(response);
                    }
                });
            });
        </script>
    }
    
        public class AjaxDemoController : Controller
        {
            [HttpGet]
            public IActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            public async Task<ActionResult> QueryB(string reply, string l_frompage)
            {
                var result = await DummyTask();
                return Ok($"{reply} {l_frompage}");
            }

    I recommend using dev tools to debug your code.  Also we cannot see the controller name or your route mapping.  

    Thursday, October 3, 2019 7:46 PM
  • User1941728045 posted

    Can you let me know what you need me to provide so that you can assist me in getting the redirect to work ? My HttpPost QueryB works fine as everything works fine up until the page comes back.

    The button that is being clicked is sitting on a Partial View .. And because of this i was advised to use Ajax/Jquery. I wouldnt mind using form collection if it works within the Partial View. Let me know

    Im not too familiarwith Ajax/Jquery .. so, please bear with me.

    The controller is called Travel. Not sure what you mean by route mapping .. I dont have any special routing enabled. I've left it all standard.

    Ta,

    Thursday, October 3, 2019 8:14 PM
  • User475983607 posted

    This is causing the 404? 

    location.reload("/Travel/MyTlBHeaderTR");


    location.reload reloads the current page.

    Try the following bu make sure MyTlBHeaderTR exists first.

    window.location = "/Travel/MyTlBHeaderTR"

    Still, the code is over complicated.  As suggested above, you could create a standard form post and redirect.  

    Thursday, October 3, 2019 8:56 PM
  • User1941728045 posted

    Hi Guys,

    Then Can you show me the alternative with the Form post and redirect, please ..

    The textbox and button to post is on a Partial View .. once the button is clicked, i need to call my controller and insert into my DB and return the original View which had called the Partial View.

    The standard Post and Redirect was giving me problems because its from a Partial View

    Thanks,

    Thursday, October 3, 2019 8:56 PM
  • User475983607 posted

    Then Can you show me the alternative with the Form post and redirect, please ..

    Alternative to what?  You'll have an [HttpPost] Action and the Action will return with 

    return RedirectToAction("theActionName");

    The standard Post and Redirect was giving me problems because its from a Partial View

    A partial is just a reusable bit of HTML. A partial should not affect an HTML Post or Redirect.  Maybe remove the partial.

    Thursday, October 3, 2019 9:06 PM
  • User1941728045 posted

    The Main View() contains a table with clickable rows. Once a row is clicked, it takes you to a Partial View that contains some detail information about that row which was clicked. As well, within that Partial View, i have a text box where the user can enter in text and Post that to the DataBase. I have tried to do a standard Post from a partial view so that the value entered by a user would go straight to the HttpPost method .. but im unable to. I was told i need to do it via an Ajax call.

    Is there a way of doing it without me doing Ajax/Jquery ? If there is, can you provide me with an example whereby i can post a user entered value from a Partial View to a Controller without having to do it via Jquery ?

    Thanks Kindly,

    Thursday, October 3, 2019 9:13 PM
  • User475983607 posted

    Your response just does not make sense.  A partials is a construct that runs on the server.  A post goes to an action.  You can choose to return whatever HTML content (View) you like in any UI design you wish from that post.  

    Thursday, October 3, 2019 10:31 PM
  • User1941728045 posted

    As per Bruce, it was simpler to just do a form post and redirect.

    Therefore, i scrapped the Ajax/Jquery code.

    Ta,

    Sunday, October 6, 2019 7:05 PM