0

I need to send Table information from the user, to a MVC Controller using POST (to save it on Server's Session).

I see the POST's information being passed successfully using a Sniffer, but it never reaches the actual MVC Controller (it never reaches the break-point!).

My Code:

<script type="text/javascript">
    $(document).ready(function () {
        $("#btnSave").click(function () {
            var tableStr = $("#divTable").html();
            $.post("Home/Save/", tableStr, function (data) {
                if (data) {
                    alert("Great success!");
                }
                else {
                    alert("Fail!");
                }
            });
            return false;
        });
    });
</script>

<h2><%: ViewBag.Message %></h2>
<%=Ajax.ActionLink("Show Users", "LoadUsers", new AjaxOptions() { InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "divTable" }) %>

<center><div id="divTable"></div></center>
<input type="button" id="btnSave" value="Save" />

Controller:

    [HttpPost]
    public ActionResult Save(string tableHtml)
    {
        Session["TableStr"] = tableHtml;
        return new JsonResult() { Data = true };
    }

What am I doing wrong?? Been googling for hours!

Is there a simpler way I can pass this information to my Server's Session? This has to be AJAX (A-Synchronic call).

4
  • been googling for hours - none of the results mentioned adding [HttpPost] to your Save action? Commented Jun 18, 2012 at 13:47
  • If you're getting a 404 error, try adding the [HttpPost] attribute above your public controller method. Commented Jun 18, 2012 at 13:49
  • 1. Adding the [HttpPost] didn't change anything. 2. I'm not getting any 404, it looks like the view simply resets (without saving the variable in the Session). Commented Jun 18, 2012 at 13:52
  • The view resets because you're returning a ViewResult not JsonResult. See my answer below. Commented Jun 18, 2012 at 14:52

4 Answers 4

2

You do need [HttpPost] if you're doing a post, do not remove that even if it still didn't work. You also need to make sure you're returning JSON data.

Assuming you did that and your controller is actually being referenced correctly, you can try explicitly declaring your AJAX element to make sure everything is being passed correctly, including the name of your payload:

$("#form").submit(function () {
    $.ajax({           
       type: 'POST',
       dataType: 'json',
       url: '/Home/Save/', 
       data: { tableHtml: tableStr }, 
       success: function (data) {
            ...
       }
    });
});

[HttpPost]
public JsonResult Save(string tableHtml)
{
    Session["TableStr"] = tableHtml;
    return Json(new { Data = "true" });
}
Sign up to request clarification or add additional context in comments.

Comments

1

looks like your missing a /, try this

$.post("/Home/Save/", tableStr , function (data) {
            if (data) {
                alert("Great success!");
            }
            else {
                alert("Fail!");
            }
        });

here is a blog post on doing this http://bob-the-janitor.blogspot.com/2011/11/more-ajax-with-mvc-using-partial-views.html

Comments

1

I think you need to decorate your method with httppost:

[HttpPost]
public ActionResult Save(string tableHtml)
{
    Session["TableStr"] = tableHtml;

    return new JsonResult() { Data = true };
}

Also, make sure that the path is correct to your controller. If you are sure, use the $.ajax call instead of $.post and make use of the error callback to see what went wrong.

Comments

0

I see a few things wrong with this.

  1. You are calling $("#Form").Submit()...., you have no element with the ID form. Try putting <form id="theForm"> and changing your call to $("#theForm").submit()...

  2. You are setting your tableStr variable when the page loads. Looking at your example, this is empty. Then, you call an Ajax actionlink to populate the div. However, you never update your tableStr variable again with the AJAX received content. You will be sending an empty string to the server once you get this to work.

  3. Why are you using a FORM element to do this? Forms are typically used to collect information from the user to submit to the server, which in this example, you are not collecting data, only sending the content of a div. You could have a button without the form to do the same thing and will grab whatever is in the "DivTable" element at the time of the button click:

Javascript

$(document).ready(function () {
    $("#myButton").click(function () {
       var tableStr = $("#divTable").html();
       $.ajax({           
          type: 'POST',
          dataType: 'json',
          url: '/Home/Save/', 
          data: { tableHtml: tableStr }, 
          success: function (data) {
             alert("Great success!");
           },
          error: function(data){
             alert('fail');
          }
       });
    });
  });

Controller

[HttpPost]
public ActionResult Save(string tableHtml)
{
    Session["TableStr"] = tableHtml;

    return new JsonResult() { Data = true };
}

HTML

<center><div id="divTable"></div></center>
<input type="button" id="myButton" value="Save some stuff"/>

4.Why is this necessary anyways? Looking at this code, you appear to be populating a list from an Ajax call to the server (Using the Ajax.ActionLink), then resubmitting that list back to the server to store in session? If that is right, just store the information in session when you call your Ajax link.

public ActionResult LoadUsers()
    {
        var UserInfoHtmlString = GetYourUserInfo();
        Session["TableStr"] = UserInfoHtmlString ;
        return UserInfoHtmlString;
    }

3 Comments

This looks like the right way!! but it's still not 100% - First, I need to save the State of the table only upon a "Save" button click, and not while loading the list (user can change information of the table). Now, your code seems to be working (getting the alerts!), but on my Action, the variable "string tableHtml" is null, and it's saving nothing in the Session. any ideas why?
@user1461793 - call alert(tablrStr) and ensure that you are grabbing the HTML like you think you are. If that is blank, we know where to start looking for the problem
@user1461793 - also, I updated my method to use the .ajax method and not the .post method, I think my fast pseudo code may not have been posting the correct information.

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.