MudTable WASM, populating state on page load - blazor-webassembly

Can't find a code sample for this in any of the documentation. Using MudTable ServerData feature, want to store the tables state (page no, page size, sorting) into the url as it changes which Iv'e done:
NavigationManager.NavigateTo($"/list/MyEntity/?PageNo={state.Page}&PageSize={state.PageSize}&SortLabel={state.SortLabel}&SortDirection={(state.SortDirection == MudBlazor.SortDirection.Ascending ? "asc" : "desc")}&Filter={Filter}", false);
However on loading the page, I want to push these parameters into the MudTable
table.CurrentPage = PageNo;
table.RowsPerPage = PageSize;
await table.ReloadServerData();
however I get warnings that I can't use 'table.CurrentPage' outside of component. Any way to implement what I want in current version of MudTable?

Assigning the values to component parameters in code is not the Blazor way. All you need to do is to set them in Razor like this:
<MudTable Items="#Elements" CurrentPage="PageNo" RowsPerPage="PageSize">
...
<PagerContent>
<MudTablePager />
</PagerContent>
</MudTable>
Here is a fiddle to play around with live. It shows that setting the two parameters in razor works. https://try.mudblazor.com/snippet/QaQlvFvLmZkKlaWQ

I think this should do the trick. Sadly, NavigateTo() looks broken.
#inject NavigationManager NavigationManager
<MudTable
#* ... *#
</MudTable>
#code
{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// on first render, _table is null
if (firstRender)
{
return;
}
var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
var queryComponents = QueryHelpers.ParseQuery(uri.Query);
queryComponents.TryGetValue("PageNo", out StringValues pageNo);
queryComponents.TryGetValue("PageSize", out StringValues pageSize);
int rowsPerPage = int.Parse(pageSize.First());
int page = int.Parse(pageNo.First());
_table.SetRowsPerPage(rowsPerPage);
//_table.NavigateTo(page); // this is broken
await _table.ReloadServerData();
}
}

Related

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

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.

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);
}
}

NVelocity -- #parse with embedded resources

I'm generating emails based off embedded NVelocity templates and would like to do something with dynamically included sections. So my embedded resources are something like this:
DigestMail.vm
_Document.vm
_ActionItem.vm
_Event.vm
My email routine will get a list of objects and will pass each of these along with the proper view to DigestMail.vm:
public struct ItemAndView
{
public string View;
public object Item;
}
private void GenerateWeeklyEmail(INewItems[] newestItems)
{
IList<ItemAndView> itemAndViews = new List<ItemAndView>();
foreach (var item in newestItems)
{
itemAndViews.Add(new ItemAndView
{
View = string.Format("MyAssembly.MailTemplates._{0}.vm", item.GetType().Name),
Item = item
});
}
var context = new Dictionary<string, object>();
context["Recipient"] = _user;
context["Items"] = itemAndViews;
string mailBody = _templater.Merge("MyAssembly.MailTemplates.DigestMail.vm", context);
}
And in my DigestMail.vm template I've got something like this:
#foreach($Item in $Items)
====================================================================
#parse($Item.viewname)
#end
But it's unable to #parse when given the path to an embedded resource like this. Is there any way I can tell it to parse each of these embedded templates?
Hey Jake, is .viewname a property? I'm not seeing you setting it in your code, how about you use the following:
#foreach($Item in $Items)
====================================================================
$Item.viewname
#end
I don't know why you're parsing the $Item.viename rather than just using the above? I'm suggesting this as I've just never needed to parse anything!
Please refer to this post where we've discussed the generation of templates.
Hope this helps!

Is there a better way to get ClientID's into external JS files?

I know this has been asked before, but I've found a different way to get references to controls in external JS files but I'm not sure how this would go down in terms of overall speed.
My code is
public static void GenerateClientIDs(Page page, params WebControl[] controls) {
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
foreach (WebControl c in controls) {
script.AppendLine(String.Format("var {0} = '#{1}';", c.ID, c.ClientID));
}
script.AppendLine("</script>");
if (!page.ClientScript.IsClientScriptBlockRegistered("Vars")) {
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "Vars", script.ToString());
}
}
This was I can reference the id of the aspx page in my JS files.
Can anyone see any drawbacks to doing things this way? I've only started using external JS files. Before everything was written into the UserControl itself.
Well, the method can only be used once in each page, so if you are calling it from a user control that means that you can never put two of those user controls on the same page.
You could store the control references in a list until the PreRender event, then put them all in a script tag in the page head. That way you can call the method more than once, and all client IDs are put in the same script tag.
Something like:
private const string _key = "ClientIDs";
public static void GenerateClientIDs(params WebControl[] controls) {
Page page = HttpContext.Current.Handler As Page;
List<WebControl> items = HttpContext.Current.Items[_key] as List<WebControl>;
if (items == null) {
page.PreRender += RenderClientIDs;
items = new List<WebControl>();
}
items.AddRange(controls);
HttpContext.Current.Items[_key] = items;
}
private static void RenderClientIDs() {
Page page = HttpContext.Current.Handler As Page;
List<WebControl> items = HttpContext.Current.Items[_key] as List<WebControl>;
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
foreach (WebControl c in items) {
script.AppendLine(String.Format("var {0} = '#{1}';", c.ID, c.ClientID));
}
script.AppendLine("</script>");
page.Head.Controls.Add(new LiteralControl(script));
}
Check this out: http://weblogs.asp.net/joewrobel/archive/2008/02/19/clientid-problem-in-external-javascript-files-solved.aspx
Looks like it takes care of the dirty work for you (something like Guffa's answer). It generates a JSON object (example) containing server IDs and client IDs, so you can do something like this in your JavaScript:
var val = PageControls.txtUserName.value;

Ideas on making a javascript object name unique in ASP.Net?

I've created an ASP.Net user control that will get placed more than once inside of web page. In this control I've defined a javascript object such as:
function MyObject( options )
{
this.x = options.x;
}
MyObject.prototype.someFunction=function someFunctionF()
{
return this.x + 1;
}
In the code behind I've created MyObject in a startup script --
var opts = { x: 99 };
var myObject = new MyObject( opts );
When a certain button in the control is pressed it will call myObject.someFunction(). Now lets say the value of x will be 99 for one control but 98 for another control. The problem here is that the var myObject will be repeated and only the last instance will matter. Surely there's a way to make the var myObject unique using some concept I've haven't run across yet. Ideas?
Thanks,
Craig
Your Javascript like this:-
function MyObject(options) { this.x = options.x; }
MyObject.prototype.someFunction = function() { return this.x + 1; }
MyObject.create(id, options) {
if (!this._instances) this._instances = {};
return this._instances[id] = new MyObject(options);
}
MyObject.getInstance(id) { return this._instances[id]; }
Your startup javascript like this:-
MyObject.create(ClientID, {x: 99});
Other code that needs to use an instance (say in the client-side onclick event)
String.Format("onclick=\"MyObject.getInstance('{0}').someFunction()\", ClientID);
Note the low impact on the clients global namespace, only the MyObject identifier is added to the global namespace, regardless of how many instances of your control are added to the page.
If it is just one value, why not have the function take it as a parameter and build your onclick handler so that it puts the correct value in for each control. If it is more complex than that, then consider making options an array and, for each control, insert the correct options into the spot in the array that corresponds to each particular control. Then pass the proper index into the array into the function.
I do this by using ScriptManager.RegisterClientScriptBlock to register a string as a JavaScript block on the client side. I can then modify my script string using {0}, {1}..,{n} place holders to inject necessary ids. It depends on the structure of your code as to if this is the most elegant fashion, but it works in a pinch. You could then inject variable names using references to Me.ClientID.
You can make the value of "x" static and access it anywhere in the code, such as:
function MyObject( options ) { MyObject.x = options.x; }
MyObject.x = 99; // static
MyObject.prototype.someFunction = function () { return MyObject.x + 1; }
This way you can access MyObject.x anywhere in your code, even without re-instanciating MyObject.
Excellent solution Anthony. The other solutions offered were as good and I did consider them but I was looking for something a little more elegant like this solution.
Thanks!

Resources