0

I'm building a SMS system. I've contacts and want to allow the user to select multiple contacts and send message to them.

I want to maintain a user's selection of contacts temporarily so that when the user hits SEND button i can process that list.

I'm using C# MVC4 with Ajax calls to code behind method to create either a TempData or Session variable. The problem is, after setting the TempData and Session variable i want to display this data on the screen, but both TempData and Session Variable are empty. As a test i'm just saving "ok" in Session Test Variable. If you have a better idea that will serve the same purpose it'll be grate too.

Thanx

//Javascript function residing on the View
function addToSendList(id) {
    $.ajax({
        type: "POST",
        url: "AddToSendList",
        contentType: "application/json;chartset=utf-8",
        dataType: "json",
        data: "{'id':'" + id + "'}",
        success: function (data) {
            alert(@Session["test"]);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

//Method on Controller that is called
public JsonResult AddToSendList(string id)
{
    int cid = int.Parse(id);
    List<Contact> contacts = (from c in db.Contacts
        where c.Id==int.Parse(id)
        select c).ToList();

    Session["test"] = "ok";
    return Json(contacts, JsonRequestBehavior.AllowGet);
}

EDIT sorry i made a mistake, i'm sending back the contact to be added into a list by ajax. That is where i'm having problem. How do i maintain that user selected list?

Adrian Forsius
  • 1,437
  • 2
  • 19
  • 29
Hassan Shifaz
  • 45
  • 2
  • 7

1 Answers1

0

This will not work because your are trying to execute server side code inside javascript. The server side portion will only execute when the page is initially rendered and will not have the updated value in the ajax callback.

You can save the value to session this way, but you can't access it like this in JavaScript.

You can consider passing it back with the json response from the controller instead - instead of the true flag.

return Json(Session["test"]);

success: function (data) {
                alert(data);
            }
TGH
  • 38,769
  • 12
  • 102
  • 135
  • Thanx for replying TGH, i cannot send Session cox i need to return contact back to the View. Only if i can return both, but i don't think that is allowed. – Hassan Shifaz Oct 02 '14 at 05:16
  • You can send back any object, so you can basically just include whatever info you want in that object. Just create a custom class that contains the data you want to send back. – TGH Oct 03 '14 at 04:18
  • Yah, i can create an anonymous object. Awesome. Thanx TGH – Hassan Shifaz Oct 03 '14 at 13:10