recovering from missing session state in ASP.NET MVC with Telerik Ajax - asp.net

I have a webpage which includes a telerik grid in ajax mode. The data for the grid is constructed in the controller action used to serve the view, and then stored in the session. 90% of the time its available to the ajax method used to populate the grid. And sometimes its not, which is odd. Some sort of race condition ?
public ActionResult EditImage(int productModelId, int revision)
{
ViewBag.Current = "Edit";
//Unit of work and repo generation removed from brevity
var modelToEdit = prodModelRepo.Where(p => p.ProductModelID == productModelId && p.Revision == revision).FirstOrDefault();
var vmie = new VMImageEdit(modelToEdit)
{
//init some other stuff
};
Session["vmie"] = vmie;
return View(vmie);
}
Now the telerik contorol will post back to _EISelect in order to populate its grid
// Ajax Actions for EditImage
[GridAction]
public ActionResult _EISelect()
{
var vmie = (VMImageEdit) Session["vmie"];
return View(new GridModel(vmie.Colours));
}
So if my session object is null, how can I recover - I guess I need the productModelId and Revision parameters from the original EditImage call. Are they available in the _EISelect in any way - its posted to, and the post contains nothing useful.
Oh to make this possibly harder, this page will be displayed via an inline frame.

The answer lies in the telerik ajax databinding - this can be used to pass arbitrary data in the querystring
.Select("_EISelect", "AdminProduct", new { productModelId = Model.ProductModelId, revision = Model.Revision})
which can be recovered in _EISelect as parameters. Simples.

Related

Relational Query - 2 degrees away

I have three models:
Timesheets
Employee
Manager
I am looking for all timesheets that need to be approved by a manager (many timesheets per employee, one manager per employee).
I have tried creating datasources and prefetching both Employee and Employee.Manager, but I so far no success as of yet.
Is there a trick to this? Do I need to load the query and then do another load? Or create an intermediary datasource that holds both the Timesheet and Employee data or something else?
You can do it by applying a query filter to the datasource onDataLoad event or another event. For example, you could bind the value of a dropdown with Managers to:
#datasource.query.filters.Employee.Manager._equals
- assuming that the datasource of the widget is set to Timesheets.
If you are linking to the page from another page, you could also call a script instead of using a preset action. On the link click, invoke the script below, passing it the desired manager object from the linking page.
function loadPageTimesheets(manager){
app.showPage(app.pages.Timesheets);
app.pages.Timesheets.datasource.query.filters.Employee.Manager._equals = manager;
app.pages.Timesheets.datasource.load();
}
I would recommend to redesign your app a little bit to use full power of App Maker. You can go with Directory Model (Manager -> Employees) plus one table with data (Timesheets). In this case your timesheets query can look similar to this:
// Server side script
function getTimesheets(query) {
var managerEmail = query.parameters.ManagerEmail;
var dirQuery = app.models.Directory.newQuery();
dirQuery.filters.PrimaryEmail._equals = managerEmail;
dirQuery.prefetch.DirectReports._add();
var people = dirQuery.run();
if (people.length === 0) {
return [];
}
var manager = people[0];
// Subordinates lookup can look fancier if you need recursively
// include everybody down the hierarchy chart. In this case
// it also will make sense to update prefetch above to include
// reports of reports of reports...
var subortinatesEmails = manager.DirectReports.map(function(employee) {
return employee.PrimaryEmail;
});
var tsQuery = app.models.Timesheet.newQuery();
tsQuery.filters.EmployeeEmail._in = subortinatesEmails;
return tsQuery.run();
}

KendoUI : data-bind not fully working

I created this sample locally
http://demos.telerik.com/kendo-ui/mvvm/remote-binding
In my 'update' transport, I did modify the 'ProductName' from my WebAPI
public IHttpActionResult Update(Product prod)
{
prod.Price = prod.UnitPrice * prod.Quantity;
prod.ProductName = prod.ProductName + DateTime.Now.ToString();
return Ok(prod);
}
It did update and reflect on my 'dropdownlist'.
The issue is the textbox id=products is not showing the latest productname. The textbox is binded using
data-bind="value: selectedProduct.ProductName"
How can I refresh this text box ?
Thank you.
All is same except this
update: {
url: "/Product/Update",
contentType: "application/json",
type: "POST"
},
and this.
parameterMap: function (data, type) {
return kendo.stringify(data);
}
If these changes are not made; my webapi will not receive any value.
I notice like the binding somehow got broken momentarily; is it because its indirectly reference using the var 'selectedProduct' ?
The reason, I believe, that your textbox is not updating is because of two reasons: 1) you're changing the data on the server instead of the client, and 2) the textbox is tied to the selectedProduct variable which is in no way tied to the data source.
In other words, when you submit the update, because your dropdown list is bound to the productSource data source, it's data gets updated automatically and the list is refreshed to show you the changes. This is expected. On the other hand, selectedProduct is not tied to the data source in any way, so, it still holds the old value before the update was called.
The solution is you have to manually update selectedProduct after the update request returns.

ASP.net any way to cache things like this?

I have a function called on every single page:
/// <summary>
/// Gets the date of the latest blog entry
/// </summary>
public static DateTime GetNewestBlogDate()
{
DateTime ReturnDate = DateTime.Now.AddDays(30);
using (var db = new DataClassesDataContext())
{
var q = (from d in db.tblBlogEntries orderby d.date descending select new {d.date}).FirstOrDefault();
if (q != null)
ReturnDate = q.date;
}
return ReturnDate;
}
It works like this website, it gets the latest blog entry date and if it's greater than the users cookie value it displays a new icon next to the blog link.
It seems rather wasteful to keep calling this function per page request, called 1:1 on the number of page requests you have. Say you have 30,000 page views per day, that's 1,250 database queries per hour.
Is there any way I can cache this results, and have it expire say every hour?
I'm aware it's a bit of a micro optimisation, but given 10 or so similar functions per page it might add up to something worthwhile. You could denormalise it into a single table and return them all in one go, but I'd rather cache if possible as it's easier to manage.
Since it's not based on the user (the cookie is, but the query doesn't seem to be) - you can just use the standard ASP.NET Cache.
Just insert the result with an expiration of 1 hour. If you like, you can even use the callback to automatically refresh the cache.
Assuming you've stored it into MS-SQL, you could even use a SqlCacheDependency to invalidate when new data is inserted. Or, if your inserting code is well-factored, you could manually invalidate the cache then.
Just use the ASP.NET Cache object with an absolute expiration of 1 hour. Here's an example of how you might implement this:
public static DateTime GetNewestBlogDate()
{
HttpContext context = HttpContext.Current;
DateTime returnDate = DateTime.Now.AddDays(30)
string key = "SomeUniqueKey"; // You can use something like "[UserName]_NewestBlogDate"
object cacheObj = context.Cache[key];
if (cacheObj == null)
{
using (var db = new DataClassesDataContext())
{
var q = (from d in db.tblBlogEntries orderby d.date descending select new { d.date }).FirstOrDefault();
if (q != null)
{
returnDate = q.date;
context.Cache.Insert(key, returnDate, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
}
}
else
{
returnDate = (DateTime)cacheObj;
}
return returnDate;
}
You haven't indicated what is done with the returned value. If the returned value is displayed the same way on each page, why not just place the code along with the markup to display the result in a user control (ASCX) file? You can then cache the control.
Make it a webmethod with a CacheDuration?
[WebMethod(CacheDuration=60)]
public static DateTime GetNewestBlogDate()

MVC ViewData not rendering in View

I have the following code in my post action method for Edit.
JobCardService.Update(viewData.JobCard);
var js = new JavaScriptSerializer();
ViewData["Notifications"] = js.Serialize(new {NoteificationType = "Success", Message = "The installtion was successfully updated"});
return RedirectToAction("Index");
However, on the client, ViewData is null/empty, i.e. this client code
var notifications = eval("<%= ViewData["Notifications"]%>");
renders as
var notifications = eval("");
I'm sure I'm doing something small wrong.
ProfK - I think (as you'll no doubt be aware) you'll have to parse that json result in javascript once you get into your index view via the redirect. the jquery .getJson() method would seem most appropriate: http://api.jquery.com/jQuery.getJSON/
Also, as you're doing a RedirectToAction, then the context of the ViewData will be lost. In that case, you want to use TempData as a drop in replacement. Below is an example of what you could try:
jim
[edit] - not sure if this would work:
// in the controller
TempData["Notifications"] = js.Serialize(...);
// in the index view
function getMyJsondata() {
var json = $.getJson('<%=ViewContext.TempData["Notifications"] %>');
}
or as per your amendment to the question, try this:
// alternative in index view
eval("(" + "<%= TempData['Notifications']%>" + ")");
give it a go...
adendum:
to quote from a previous SO question on Tempdata vs ViewData: What is TempData collection used for in asp.net MVC?
TempData is used to share data between
controller actions. If your controller
does a RedirectToAction and the target
action needs data (perhaps a
particular model instance) to act
upon, you can store this data in
TempData. Using TempData is similar to
storing it in the session, but only
for one round-trip. You use TempData
when you need to pass data to another
controller action rather than a view
for rendering.

Postback problem for my custom control load wizard

I have some problem that happens when controls are loaded in init and it still doesn't help me to get proper postback event fired on time.
I am trying to create a rich wizard control that will enable switching, links with description, completely customized steps, integration of substeps - by using dynamic control load that is avoids standard asp.net wizard way of loading.
Idea is to have on left part navigation, on right part content, or substeps that are run from right part and that go over whole area.
Download source project
Ok, I re-read the question, and here is what you have to do. You have to re-load these controls on each postback, give them always the same "Id". This can be done in Page_Init or in Page_Load event. And of course, you have to re-attach event handlers on each post back.
Many thanks.. well i found the answer - id was the problem, in load control method. I was doing this wizard.. well most of things work now.
If someone is interested to see how does this works.. there are some updates:
public void LoadSplitViewControl(string path)
{
SwitchNavigationView(NavigationView.SplitView);
LastNavigationView = NavigationView.SplitView;
LoadControl(SplitControlLoader, path, "LoadedControlSplit");
}
public void LoadSingleViewControl(string path)
{
SwitchNavigationView(NavigationView.SingleView);
LastNavigationView = NavigationView.SingleView;
LoadControl(SingleControlLoader, path, "LoadedControlSingle");
}
public void LoadSingleViewControlAsClear(string path)
{
SwitchNavigationView(NavigationView.SingleView);
LastNavigationView = NavigationView.SingleView;
LoadControlAsClear(SingleControlLoader, path, "LoadedControlSingle");
}
private void LoadControl(PlaceHolder holder, string path, string ID)
{
UserControl ctrl = (UserControl)Page.LoadControl(path);
ctrl.ID = ID;
LastControlPath = path;
holder.Controls.Clear();
holder.Controls.Add(ctrl);
}
//as i am using steps loaded controls using splitview and substeps controls using single view sometimes viewstate will not be valid so error will be thrown but u can resolve this by using LoadSingleViewControlAsClear that will load below method.
private void LoadControlAsClear(PlaceHolder holder, string path, string ID)
{
UserControl ctrl = (UserControl)Page.LoadControl(path);
ctrl.ID = ID;
LastControlPath = path;
ctrl.EnableViewState = false;
holder.Controls.Add(ctrl);
}
/another cool idea i am using for such an wizard is that i am not using viewstate but rather session object for saving values collected over steps. My session object key is generated by authenticated username and pageguid - so u can have many loaded pages and each of them will handle different session object./
public Guid PageGuid
{
get
{
if (PageGuidField.Value == "")
{
var _pageGuid = Guid.NewGuid();
PageGuidField.Value = _pageGuid.ToString();
return _pageGuid;
}
return new Guid(PageGuidField.Value);
}
}

Resources