How do you link to other razor pages and include a query string parameter in Blazor WASM? - razor

I've got a Blazor WASM app. It has two razor pages:
Documentation.razor:
#page "/documentation"
ViewRecord.razor:
#page "/documentation/ViewRecord"
I have a DocumentationController too.
I want to create a few hyperlinks within the Documentation razor page that have hyperlinks in this format:
/Documentation/ViewRecord?recordtype=randomWord1
/Documentation/ViewRecord?recordtype=randomWord2
/Documentation/ViewRecord?recordtype=randomWord3
Is there a cleaner way to do this, similar to using ActionLinks, instead of having to do something like this:
link1
link2
link3

This is the beauty of Blazor and Razor Components, if you find you want to something, you can create a re-usable component for it yourself. Complete flexibility. Say for instance we have the following component:
UrlBuilder.razor
#if (!string.IsNullOrEmpty(FullUrl))
{
#LinkDesc
}
#code
{
[Parameter]
public string LinkDesc { get; set; }
[Parameter]
public string Controller { get; set; }
[Parameter]
public string Action { get; set; }
[Parameter]
public string UrlParameter { get; set; }
private string FullUrl { get; set; }
protected override void OnInitialized()
{
FullUrl = $"{Controller}/{Action}?{UrlParameter}";
}
}
You can then access that component anywhere through your application like so:
<UrlBuilder LinkDesc="link 1" Controller="Documentation" Action="ViewRecord" UrlParameter="#word3" />
Is that any easier than creating a a href manually? Absolutely not, however, you could customize it to your delight.

Related

Lambda Expression - Error Cannot implicitly convert type `vicoapi.Pictures' to `System.Collections.Generic.List<vicoapi.Pictures>' (CS0029)

Hello Together following my Code:
public class SampleData : DropCreateDatabaseIfModelChanges<VicoTvEntities>
{
protected override void Seed(VicoTvEntities context)
{
var pictures = new List<Pictures>{
new Pictures { Name = "Testbild", Url="localhost/test" }
};
var user = new List<User>{
new User{Username="Muster", Password="Pass",Email="max.muster#mustermail.com",Bio="Musterbiografie", Pictures = pictures.Find(pic => pic.Name == "Testbild")}
};
}
}
}
I try to build an API and at the moment, I work on the connection of the DB to the code. I'm following this tutorial: https://www.asp.net/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-4
My Problem is, whenever I try to add the Picture it won't work, because of this converting error. How can I avoid this problem and implement the picture to the User.
My Source Tree looks like this:
Source Tree
The User Class looks as following:
public class User
{
public int IdUser { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Bio { get; set; }
public List<Pictures> Pictures { get; set; }
public List<Follow> Following { get; set; }
public List<Follow> Followed { get; set; }
}
The Error I get looks like this:
/Users/username/vicotv-Backend/vicoapi/vicoapi/Models/SampleData.cs(126,126): Error CS0029: Cannot implicitly convert type `vicoapi.Pictures'to System.Collections.Generic.List' (CS0029) (vicoapi)
Although you don't show the class here, I'm fairly certain that your User class has a property defined something like this:
public List<Pictures> Pictures { get; set; }
If that is the case, you need to assign the property to the whole list like this:
user.Pictures = pictures
If you want a user to only be able to have one picture then you need to define the Picture property on the User class like this:
public Pictures Picture { get; set; }
If you define the Picture property like this it should work with your current code.
P.S. I would definitely recommend renaming your "Pictures" class to "Picture". In general you should use the singular form for class names. Have a look at this page for more information.

Databinding in ListBox in windows phone 8.0

I want to Load Data in ListView in Listbox from web services PHP API. It can't be able to load Data. Here is my JSON class:
public class Menu
{
public string Menu_ID { get; set; }
public string Menu_name { get; set; }
public string Price { get; set; }
public string Menu_image { get; set; }
}
public class Datum
{
public Menu Menu { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
Here is code for Parsing Json Data:
var root = JsonConvert.DeserializeObject<RootObject>(e.Result);
How can I bind these Data to a ListBox? Thanks in advance.
You need to set the information in the DataContext property, for example:
ListBox1.DataContext = root;
And you just need to design it. By the way, I think it's not okay:
public Menu Menu { get; set; }
Because the variable and the class share the same name.
More information:
Quickstart: Data binding to controls for Windows Phone
Also, I suggest you to move to UWP (Universal Windows Platform) that is the future of any Windows development.

Return self referencing model in JSON format using Web Api 2 controller

I have a self referencing model called Folder and also an Entity called Content which contains the Folder Entity.
public class Folder : BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual Folder Parent { get; set; }
public virtual ICollection<Folder> Children { get; set; }
}
public class Content : BaseEntity
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string HTML { get; set; }
public string Summary { get; set; }
public int XmlConfigId { get; set; }
public int FolderId { get; set; }
public virtual Folder Folder { get; set; }
}
Here is my Application Db context
public class ApplicationDbContext: DbContext
{
public DbSet<Folder> Folders { get; set; }
public DbSet<Content> Contents { get; set; }
public ApplicationDbContext() : base("ProjectDB") {
Database.SetInitializer<ApplicationDbContext>(null);
}
}
Everything works fine if i am using a razor view to display the data and also i am able to access the The Folder property that is inside the Content Entity.
The problem is when i try to display the data using Web API.
My web API
public class ContentApiController : ApiController
{
[HttpGet]
public IEnumerable<Content> GetAllContents()
{
return _unitofwork.Contents.GetAllContents();
}
}
On the Web API, the GetAllContents() function just returns the Entity models coming directly from the Folders DBSet. It is not calling the ToList() function since i want to do lazy loading. Here is the code for the GetAllContents() function.
public IEnumerable<Content> GetAllContents()
{
return ApplicationDbContext.Contents.Include(c=>c.Folder);
}
So in order for this to work i have to add.
Configuration.LazyLoadingEnabled = false;
to my applicationDbContext constructor which i really don't want.
and also
Global.asax
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
WebApiConfig
JsonMediaTypeFormatter jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
jsonFormatter.UseDataContractJsonSerializer = false;
jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
Is there any way to expose the json data without out turning off Lazy loading. Thanks.
Just call ToList on your query, or, even better, ToListAsync:
[HttpGet]
public async Task<IEnumerable<Content>> GetAllContents()
{
return await _unitofwork.Contents.GetAllContents().ToListAsync;
}
Even if you enable LazyLoading, you cannot avoid to materialize your data before returning it to the client (and let the Serializer do its work).
In your MVC example, the framework itself enumerates the result in your View (I suppose), and thus you are not directly calling ToList, but in your scenario you have to materialize your Entities explicitly.
Please note that there is no performance issue in calling ToList/ToListAsync in your controller.

Different login page for every client (on one server)

Scenario:
Currently, we have a website tool in asp.net MVC (www.tool.com/login).
Now, the client is looking into customizing the login page for several customers and they will have their own domain (but only one server for all).
for example:
www.client1.com/login,
www.client2.com/login,
www.client3.com/login
Yell at me if this is a stupid question.
But please help and give me an idea on how to implement it.
Should I create different login htmls for each client?
Related to my comment -
Create a Table with ClientInfo in DB:
Title
BackgroundColor
Language
URL --> This has to be unique for this to work [client1, client2]. Don't save the full URL -- Just the Host
Let's say you are passing a Model --> LoginModel to your LoginPage.cshtml
public class LoginModel
{
public string UserName { get; set; }
public string Password { get; set; }
public StyleDTO ClientStyles { get; set; }
}
public class StyleDTO
{
public string Title { get; set; }
public string LogoPath { get; set; }
public string BackGroundColor { get; set; }
}
In your controller when you load View:
public ActionResult Login()
{
var clientUrl = HttpContext.Current.Request.Url.Host;
var cs = dbContext.ClientInfo.First(s => s.Url == clientUrl);
var model = new LoginModel()
{
ClientStyles = new StyleDTO()
{
Title = cs.Title,
LogoPath = cs.LogoPath,
BackGroundColor = cs.BackGroundColor
}
};
}
then in your login View (LoginPage.cshtml):
#model LoginModel
<div style="background-color: #Model.BackGroundColor">
<h1>#Model.Title</h1>
</div>
create a config file with variables for client1, client2, client3
Keep same login page html and based on HTTP_referer pick one of the config variable and render the page based on that.

How do I get rid of cannot convert method group "TextBoxFor" to non-delegate type "object"?

first time using asp.net and MVC4 on visual studio trying to create a simple form for customer to enter details for a flight booking assignment, and have this error (shown below).
I cant seem to fix it, have no idea where to look to fix it to be honest. Is there another way of creating an easier form or can someone help fix this ?
View:
#model WebsiteApplicationASSES.Models.customerdetails
#{
ViewBag.Title = "customerBooking";
}
<!DOCTYPE html />
<html></html>
</div>
<div>
#using (Html.BeginForm())
{
<table>
<tr>
<td> #Html.Label ("First Name:")</td>
<td> #Html.TextBoxFor (x=>x.customerFirstName)</td>
</tr>
}
Model:
namespace WebsiteApplicationASSES.Models
{
public class customerdetails
{
public string customerFirstName { set; get; }
public string customerSecondName { set; get; }
public int customerAge { set; get; }
public int customerTelephoneNumber { set; get; }
public string customerEmail { set; get; }
public int numberOfPassangers { set; get; }
public int passangersAge { set; get; }
}
}
""
thank you!
Try removing the space. The Razor parser will try to invoke #Html.TextBoxFor as method group and treat (x=>x.customerFirstName) as text.
It should be:
#Html.TextBoxFor(x=>x.customerFirstName)
In normal C# this would work. However, with Razor one-liners can't contain spaces, unless you surround them with parentheses: #(Html.TextBoxFor (x=>x.customerFirstName))