Using razor pages I am trying to build an ecommerce website for selling clothing and I want to use once page as a template to load both mens and womens pages. To test this could be done in my _Layout.cshtml page I use <a asp-page="/Shop" asp-route-id="Mens" class="nav-link">Mens</a> and then in:
Shop.cshtml.cs
[BindProperties]
public class ShopModel : PageModel
{
public string Status { get; set; }
public void OnGet(string gender)
{
switch (gender)
{
case "Mens":
//get men page
Status = gender;
break;
case "Womens":
//get womens page
break;
}
}
}
Shop.cshtml
#page
#model ECommerce.Pages.Shop.ShopModel
#{
ViewData["Title"] = "Shop";
}
<p>
#Model.Status
</p>
When I debug the value of gender comes up as null, so status is never set. Am I going about this the wrong way? Any help is much appreciated, thanks!
The parameter name is gender, not id, so it should be
<a asp-page="/Shop" asp-route-gender="Mens" class="nav-link">Mens</a>
See more about anchor tag helper's route value.
If you are going to use another method other than OnGet for example OngetView you would have to put
Ver
Related
I have an application where I need to display a username and image for the current user. I could pull the data into a viewmodel and display in the view, however this would mean that i would need to do this in every controller that uses the view. Is there a way where I can global set values and call in some partial views without having to repeatedly duplicate it in each controller?
Sounds to me like you need to call a child action from your _Layout.cshtml. Here's how it could look.
First from what you have said I am assuming your viewModel will be this
public class UserDisplayViewModel
{
public string UserName { get; set; }
public string ImageUrl { get; set; }
}
You will need a controller that is responsible for getting the username and image data.
It would look like this
public class UserController : Controller
{
[ChildActionOnly]
public ActionResult _userDisplay()
{
var viewModel = GetUserNameAndImage();
return View(viewModel);
}
private UserDisplayViewModel GetUserNameAndImage()
{
//code for getting the username and image data
}
}
You would call the child action from your _layout.cshtml file like this
#Html.Action("_userDisplay", "User")
It goes wherever you want the username and image to appear in your HTML.
You will also need a partial view called _userDisplay.cshtml which will contain the markup for how you want to display your username and image. Here's a very basic example
#model UserDisplayViewModel
#{
Layout = null;
}
<p>
Username: #Model.UserName
</p>
<p>
<img src="#Model.ImageUrl"/>
</p>
I have razor pages .
I have prepared in a handler a list of(visitorTypes)
I only want to bind them . there is something that i have missed , but i dont know what
Here is my c# code
[ModelBinder(Name ="Visitors")]
public ICollection<VisitorType> VisitorTypes { get; set; }
public IActionResult OnGetListOfVisitorTypeAsync()
{
VisitorTypes = _db.VisitorTypes.ToList();
return RedirectToPagePermanent("/Visitors",VisitorTypes);
}
And here is my razor page
<div class="container">
<form method="get" asp-page-handler="ListOfVisitorType" >
#foreach (var item in Model.VisitorTypes)
{
<label>#item.VisitorTypeName.ToString() </label>
}
</form>
</div>
can someone please explain what im doing wrong
(I have tried to return the list , i have tried to make it a void method , but none of them works with me )
Here Is The modal
private string _VisitorTypeName { get; set; }
public string VisitorTypeName { get {return _VisitorTypeName; } set { _VisitorTypeName = value; } }
ICollection<Visitor> Visitors { get; set; }
What if you generate your data when your View get loaded, something like this:
public IActionResult Visitors()
{
VisitorTypes = _db.VisitorTypes.ToList();
return View(VisitorTypes);
}
You may have passed wrong model with "#model ?" in razor page.
This is pretty Simple
First you need to know how actually MVC works and what it's:
MVC is a architectural pattern , we keep all things loosely coupled in terms of MODEL, View and Controller
So it's doesn't means that cannot write code directly in "Razor View",
For example how we write JavaScript directly in HTML or View. for decoupling purpose we create .JS file to separate script code from View(HTML).
Now comes to actual work
First before accessing List(VisitorTypes) it must be declare and initialize with value in the razorview itself
#{
List<VisitorTypes> listVisitorTypes = _db.VisitorTypes.ToList();
}
And finally render the list:
#foreach (var item in listVisitorTypes )
{
#item.VisitorTypeName.ToString()
}
I'm a beginner in C# MVC, but I'm working on some project.
I've searched through Internet and found no solution matching my question. None of the answears solved my problem. The problem is: how to loop through every project (as you will see in code fragments below) and display them in view.
Project model code:
public class AddProjectViewModel
{
[Required]
[StringLength(50, ErrorMessage = "Project name length is too long. Maximum lenght is 50 char.")]
public string ProjectName { get; set; }
[Required]
[StringLength(50, ErrorMessage = "Description length is too long. Maximum lenght is 50 char.")]
public string Description { get; set; }
}
Project controller code:
public ActionResult Index()
{
var loggedUser = _workContext.GetUserId();
var userProjects = _userProjectsRepository.GetAllEntity().Where(x => x.UserId == loggedUser);
var model = new Models.ProjectViewModels.ShowUserProjectsViewModel();
model.Projects = userProjects;
return View(model);
}
The idea is: when the page loads up, display every project that logged user can see.
I've tried something like this, but it doesn't work:
#model IEnumerable<CarPooling.Website.Models.ProjectViewModels>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#foreach (var item in Model)
{
<div>
<p>#Html.DisplayFor(m=>item)</p>
</div>
}
Please, be patient with me and thanks for every response.
In your controller you are passing to your View a ShowUserProjectsViewModel object, but then you declare your model as IEnumerable<CarPooling.Website.Models.ProjectViewModels> inside your .cshtml View.
Use the same model type you passed inside your controller, and also remember to use the same properties defined in your ViewModel classes, as shown below:
#model ShowUserProjectsViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#foreach (var item in Model.Projects)
{
<div>
<p>#Html.DisplayFor(m=>item.ProjectName)</p>
</div>
}
My controller returns a string which is a url of an image of an external site.
How do I display that url on the view.
I appreciate your help.
AngryHacker is correct. I am just expanding AngryHacker's answer with some code example.
Add a property in your ViewModel for the image url and return it in the first get call. Then use it in the View. Thus you are avoiding an unnecessary http request to to the action again
public class UserProfileViewModel
{
public string DisplayName { set;get;}
public string GravatarURL { set;get;}
}
and in your ACtionMethod,
public ActionResult Get(int id)
{
UserProfileViewModel objVm=new UserProfileViewModel();
objVM.GravatarURL="http://www.externalsite.com/image/tiyra.jog";
//Set other properties also.
return View(objVm);
}
and in the View which is strongly typed to your UserProfileViewModel,
#model UserProfileViewModel
<h2>"#Model.DisplayName </h2>
<img src="#Model.GravatarURL" />
<p>The image is loaded from #Model.GravatarURL</p>
Make the URL part of your model and just reference it in the View.
Perhaps you're missing the part where you have to HTML-encode your output with the <%: %> tag, a la:
<%: Html.Label(ViewData["PicUrl"].ToString()) %>
...or, if it's a string property on your model...
<label><%: Model.PicUrl %></label>
This seems like it should be prettty easy - but I just can't get it to work!
I have an enum in my model, which I want to display as a list of checkboxes. The user can select multiple checkboxes, and I want to save this in the database.
So the enum is like so (approx 20 elements unabridged):
public enum ReferrerType
{
[Description("No Data")]
NoData = 9999,
[Description("Father or Mother")]
Parents = 1,
[Description("Brother or Sister")]
Sibling = 2,
[Description("Other")]
Other = 10
}
Whereby the Description is what is shown on the UI, and the numeric value is what is to be saved in the database. The numbers have to remain as listed, as they go directly into a stats package.
I then defined a Referrer class:
public class Referrer
{
public virtual Guid Id { get; private set; }
public virtual ReferrerType{ get; set; }
}
I realise this might be an odd (anti)pattern. I developed it in haste, and am repenting at leisure. Any advice on improving this model would also be much appreciated!
My controller sets up the list:
private static IList<string> GenerateReferrerList()
{
var values = from ReferrerType e in Enum.GetValues(typeof(ReferrerType))
select new { Name = e.ToDescription() };
return values.Select(x => x.Name).ToList();
}
And I use it in my View like this:
<div class="radio-boolean form-field" id="Referrers">
<p class="form-field-attribute"> <span class="label">Referred By </span> </p>
<% for (var i = 0; i < ((IList<string>)ViewData["ReferrerList"]).Count; i++)
{ %>
<p class="form-field-value">
<%= Html.CheckBox(string.Format("Referrers[{0}].Type", i) ) %>
<label for="Referrers"> <%= ((IList<string>)ViewData["ReferrerList"])[i]%></label>
</p>
</div>
And it doesn't work! I guess I'm missing something obvious, but I can't work out what. There are no errors - just an empty database table where referrers should be...
As always, any help much appreciated!
Let's take a moment and see what do we need here. We need to show a form which will contain multiple checkboxes (one for each value of the enum) and an associated label (this label should come from the Description attribute use on the enum). When this form is submitted we want to fetch all the values that the use has checked.
So as always once we have clear definition of what we are trying to do we introduce our view model:
public class MyViewModel
{
public bool IsChecked { get; set; }
public ReferrerType ReferrerType { get; set; }
public string Text { get; set; }
}
Then we write a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = Enum.GetValues(typeof(ReferrerType)).Cast<ReferrerType>().Select(x => new MyViewModel
{
ReferrerType = x,
Text = x.ToDescription() // I guess that's an extension method you wrote
});
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
...
}
}
And finally a strongly typed view corresponding to the Index action of our controller (~/Views/Home/Index.aspx):
<% using (Html.BeginForm()) { %>
#Html.EditorForModel()
<input type="submit" value="OK" />
<% } %>
and the last part is the corresponding editor template (~/Views/Home/EditorTemplates/MyViewModel.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.MyViewModel>" %>
<%= Html.CheckBoxFor(x => x.IsChecked) %>
<%= Html.HiddenFor(x => x.ReferrerType) %>
<label><%: Model.Text %></label>
Now when this form is submitted inside the POST index action you would get a list of all enums with a corresponding boolean value indicating whether the user checked it or not.
OT: Don't perform excess actions:
return (from e in Enum.GetValues(typeof(ReferrerType))
select e.ToDescription()).ToList();
or just
return Enum.GetValues(typeof(ReferrerType)).Select(e => e.ToDescription()).ToList();