Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of TempData in ASP.NET MVC3?

I have an ASP.NET MVC3 application where my action generates a list of ids that I want to make available to a subsequent AJAX request. This is so that I can run a long process in the background and poll on it. The list of ids are the necessary input to this long running process. I don't want to pass them in the URL as a parameter, because the list could potentially be very long and cause issues in IE.

My Controller

public ActionResult Run()
{
    List<MyObjs> objs = _db.MyObjs.ToList<MyObjs>();

    string uniqueId = Guid.NewGuid().ToString();
    ViewData["UniqueID"] = uniqueId;
    TempData["ObjIdList" + uniqueId] = String.Join(",", objs .Select(o => o.ObjID).ToArray<int>());

    return View(objs);
}            

public void StartProcess(string uid)
{
    string ids = TempData["ObjIdList" + id].ToString().Split(',');
    ...        
}

My View

var uniqueId = '@ViewData["UniqueID"]';

$(document).ready(function (event) {
    $('#startProcess').click(function () {
        $.post("/Scheduler/StartProcess", { uid: uniqueId }, function () {
            getStatus();
        });
        event.preventDefault;
    });
});

function getStatus() {
    var r = new Date().getTime(); // cache killer for IE
    var url = '/Scheduler/GetCurrentProgress/' + uniqueId + "?r=" + r;
    $.get(url, function (data) {
        if (data != "100") {
            $('#status').html(data);
            setTimeout(function () { getStatus(); }, 100);
        } else {
            $('#status').html("Done");
        };
    });
}

This is working in my intial test, albeit on my laptop with one concurrent user. Is this safe, or is there a better way to pass this data?

like image 859
Paul Avatar asked Oct 04 '12 22:10

Paul


1 Answers

Brandon

TempData is like ViewData, except that it persists for two successive requests making it useful for things like passing data between two different controller actions

Jason C

TempData in MVC actually persists until retrieved. As an FYI Tempdata is actually stored in a users SessionState so it is more like SessionData than ViewData

Taken from one of my questions responses - MVC3 Controller Action Result 'Remember' Passed-in Id

Essentially TempData is like a Session Property - (stored in the SessionState) used for communication between two successive requests to the controller. As if this is a good or bad practice well in your case I think it would be perfectly fine to pass data to the tempdata but their are other options, hidden fields among them. Another good link to look at is ASP.NET MVC - TempData - Good or bad practice

like image 111
Nate-Wilkins Avatar answered Oct 02 '22 14:10

Nate-Wilkins