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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With