MVC PartialViews models - c#

I want to use a different model for my partialviews, how to do this? Do you have examples?
<div id="tabs">
<ul>
<li>first tab</li>
<li>second tab</li>
<li>third tab</li>
</ul>
<div id="tabs-1">
#{Html.RenderPartial("FirstTabView", Model)}
</div>
<div id="tabs-2">
#{Html.RenderPartial("SecondTabView", Model)}
</div>
<div id="tabs-3">
#{Html.RenderPartial("ThirdTabView", Model)}
</div>
</div>

You could have sub-models as part of your main model, such as:
public class YourModel
{
public FirstTabModel FirstTab { get; set; }
public SecondTabModel SecondTab { get; set; }
public ThirdTabModel ThirdTab { get; set; }
}
Then you can do:
<div id="tabs-1">
#{Html.RenderPartial("FirstTabView", Model.FirstTab)}
</div>
<div id="tabs-2">
#{Html.RenderPartial("SecondTabView", Model.SecondTab)}
</div>
<div id="tabs-3">
#{Html.RenderPartial("ThirdTabView", Model.ThirdTab)}
</div>

Related

dotnet 5 MVC 404 error when I post to action

I have a page that is supposed to submit data for a patient evaluation. The page to submit the evaluation comes up fine. It is based on a ViewModel. Here is the ViewModel:
public class SPEPatientEvalVM
{
public int Id { get; set; }
public int ApptId { get; set; }
public int ActivityID { get; set; }
public int VendorID { get; set; }
public int PatientID { get; set; }
[Required(ErrorMessage ="A selection is required.")]
public int OverallRating { get; set; }
[Required(ErrorMessage = "A selection is required.")]
public int AppearProfessComp { get; set; }
[Required(ErrorMessage = "A selection is required.")]
public int EffGatheredInfo { get; set; }
[Required(ErrorMessage = "A selection is required.")]
public int ListenActively { get; set; }
[Required(ErrorMessage = "A selection is required.")]
public int EstabPersRapport { get; set; }
[Required(ErrorMessage = "A selection is required.")]
public int AppropExploreMyFeelings { get; set; }
[Required(ErrorMessage = "A selection is required.")]
public int AddressedMyFeelings { get; set; }
[Required(ErrorMessage = "A selection is required.")]
public int MetMyNeeds { get; set; }
public string PatientComments { get; set; } = String.Empty;
public DateTime DateSubmitted { get; set; }
}
This is mapped and reverse mapped to the model using IMapper.
Anyway this is my controller code:
[HttpGet("[controller]/[action]/{IDAppt}/{ActivityID}/{VendorID}/{PatientID}")]
public async Task<IActionResult> AddSPEPatientEval(int IDAppt, int ActivityID, int VendorID, int PatientID)
{
var patientChoice = GetPatientChoiceList();
patientChoice[0].Selected = true;
ViewBag.PatientChoice = patientChoice;
var evalParams = await _speRepo.GetOpenPatientEval(IDAppt);
ViewBag.Patient = evalParams.SPEPatient;
var speEval = new SPEPatientEvalVM
{
ApptId = IDAppt,
ActivityID = ActivityID,
VendorID = VendorID,
PatientID = PatientID
};
return View(speEval);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddSPEPatientEval(SPEPatientEvalVM model)
{
var patientChoice = GetPatientChoiceList();
patientChoice[0].Selected = true;
ViewBag.PatientChoice = patientChoice;
model.DateSubmitted = DateTime.Now;
if (ModelState.IsValid)
{
var spePatientEval = _mapper.Map<SPEPatientEval>(model);
var success = await _speRepo.AddSPEPatientEval(spePatientEval);
if (!success)
{
return View(model);
}
return View("Index");
}
return View(model);
}
This is all for the form AddSPEPatientEval.cshtml
#model SPEPatientEvalVM
#{
ViewData["Title"] = "AddSPEPatientEval";
}
<div class="col-md-8 m-auto">
<h1 class="text-center">Patient SPE Evaluation</h1>
<hr />
</div>
<div class="col-md-8 m-auto">
<div class="row">
<div class="col-md-12">
<form asp-controller="SPE" asp-action="AddSPEPatientEval" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ApptId" />
<input type="hidden" asp-for="ActivityID" />
<input type="hidden" asp-for="VendorID" />
<input type="hidden" asp-for="PatientID" />
<input type="hidden" asp-for="DateSubmitted" value="#String.Format("{0:MM/dd/yyyy}", DateTime.Now)" />
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label asp-for="OverallRating" class="control-label">As #ViewBag.Patient, rate your overall level of satisfaction with this encounter.</label>
<select asp-for="OverallRating" class="form-control"
asp-items="#(new SelectList(ViewBag.PatientChoice, "Value", "Text"))"></select>
<span asp-validation-for="OverallRating" class="text-danger"></span>
</div>
<br />
<hr />
</div>
</div>
<br />
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label asp-for="AppearProfessComp" class="control-label">Appeared professional competent - seemed to know what s/he was
doing; inspired my comfidence; appeared to have my interests at heart.
</b></label>
<select asp-for="AppearProfessComp" class="form-control"
asp-items="#(new SelectList(ViewBag.PatientChoice, "Value", "Text"))"></select>
<span asp-validation-for="AppearProfessComp" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label asp-for="EffGatheredInfo" class="control-label">Effectively gathered information - collected information in a way that
seemed organized; began with several open-ended questions and progressed through interview using a balanced ratio of open-
to closed-ended questions; summarized periodically.
</label>
<select asp-for="EffGatheredInfo" class="form-control"
asp-items="#(new SelectList(ViewBag.PatientChoice, "Value", "Text"))"></select>
<span asp-validation-for="EffGatheredInfo" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label asp-for="ListenActively" class="control-label">Listened actively - paid attention to both my verbal and non-verbal
cues; used facial expressions/body language to express encouragement; avoided interruptions; asked questions to make sure
s/he understood what I said.
</label>
<select asp-for="ListenActively" class="form-control"
asp-items="#(new SelectList(ViewBag.PatientChoice, "Value", "Text"))"></select>
<span asp-validation-for="ListenActively" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label class="control-label">Established personal rapport - introduced self warmly; verbally/non-verbally showed interest
in me as a person, not just my condition; avoided technical jargon.
</label>
<select asp-for="EstabPersRapport" class="form-control"
asp-items="#(new SelectList(ViewBag.PatientChoice, "Value", "Text"))"></select>
<span asp-validation-for="EstabPersRapport" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label asp-for="AppropExploreMyFeelings" class="control-label">Appropriately explored my perspective - encouraged me to
identify everything that I needed to say.
</label>
<select asp-for="AppropExploreMyFeelings" class="form-control"
asp-items="#(new SelectList(ViewBag.PatientChoice, "Value", "Text"))"></select>
<span asp-validation-for="AppropExploreMyFeelings" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label asp-for="AddressedMyFeelings" class="control-label">Addressed my feelings - acknowledged and demonstrated interest in my
expressed and/orunexpressed feelings and experience.
</label>
<select asp-for="AddressedMyFeelings" class="form-control"
asp-items="#(new SelectList(ViewBag.PatientChoice, "Value", "Text"))"></select>
<span asp-validation-for="AddressedMyFeelings" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label asp-for="MetMyNeeds" class="control-label">Met my needs - worked toward a plan which addressed both the diagnosis and
my concerns about my illness.
</label>
<select asp-for="MetMyNeeds" class="form-control"
asp-items="#(new SelectList(ViewBag.PatientChoice, "Value", "Text"))"></select>
<span asp-validation-for="MetMyNeeds" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<label asp-for="PatientComments" class="control-label"></label>
<textarea asp-for="PatientComments" class="form-control"
placeholder="Please add any additional comments you would like to express about this examination."></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8 m-auto">
<div class="text-center">
<a asp-action="Index">Back to List</a>
</div>
</div>
</div>
#section Scripts {
#{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
Once the form is completed and all required fields are entered, if I hit the "Submit" button, I get:
This localhost page can’t be found
No webpage was found for the web
address:
https://localhost:5001/SPE/AddSPEPatientEval/18659/15129/235/4
HTTP ERROR 404
What am I missing guys? I am sure it is something that is in plain site. I am just have looked at it too long and cannot find what is going on.
What have I tried... I feel like everything. I have tried adding a route to the HttpPost statement. I have tried making sure all the model fields are not null. I do not know what else to try.
Thanks in advance for any help.
Your POST route should match the GET route:
[HttpPost("[controller]/[action]/{IDAppt}/{ActivityID}/{VendorID}/{PatientID}")]
Add [FromRoute] to the action parameters:
[HttpGet("[controller]/[action]/{IDAppt}/{ActivityID}/{VendorID}/{PatientID}")]
public async Task<IActionResult> AddSPEPatientEval([FromRoute]int IDAppt, [FromRoute] int ActivityID, [FromRoute] int VendorID, [FromRoute] int PatientID)
You should also change HttpGet to HttpPost.

When i try to get data from data for edit page it's showing me error

When I try to get data from data for edit page it's showing me the following error:
So I am building a website where I want to implement a edit banner form when the User can Edit his banner data.
And here is where the problem I raise, when I run the code, it return always as null.
Here is my controller:
[HttpGet]
public ActionResult EditBanner(int id)
{
var abd = (from a in _db.Banner
where id == a.BannerId
select a).FirstOrDefault();
return View(abd);
}
[HttpPost]
public ActionResult UpdateBannerDatas(BannerViewModels bnrupdate)
{
var bnrdata = _db.Banner.Where(x => x.BannerId == bnrupdate.BannerId).FirstOrDefault();
if (bnrdata != null)
{
bnrdata.BannerTitle = bnrupdate.BannerTitle;
bnrdata.BannerUrl = bnrupdate.BannerUrl;
bnrdata.BannerIndex = bnrupdate.BannerIndex;
bnrdata.BannerDescription = bnrupdate.BannerDescription;
bnrdata.BannerIndex = bnrupdate.BannerIndex;
_db.SaveChanges();
}
return Redirect("BannerDetails");
}
Here is my viewmodel:
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SZGMC.Web.Models;
namespace SZGMC.Web.Areas.Admin.ViewModels
{
public class BannerViewModels
{
public int BannerId { get; set; }
public string BannerTitle { get; set; }
public string BannerDescription { get; set; }
public string BannerImg { get; set; }
public IFormFile BannerImg1 { get; set; }
public string BannerUrl { get; set; }
public string BannerIndex { get; set; }
public int? BMasterId { get; set; }
public byte? IsDeleted { get; set; }
public virtual BannerMaster BMaster { get; set; }
}
}
Here is my model:
using System;
using System.Collections.Generic;
// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable
namespace SZGMC.Web.Models
{
public partial class Banner
{
public int BannerId { get; set; }
public string BannerTitle { get; set; }
public string BannerDescription { get; set; }
public string BannerImg { get; set; }
public string BannerUrl { get; set; }
public string BannerIndex { get; set; }
public int? BMasterId { get; set; }
public byte? IsDeleted { get; set; }
public virtual BannerMaster BMaster { get; set; }
}
}
Here is my view:
<form asp-controller="Home" asp-action="UpdateBannerDatas" enctype="multipart/form-data" method="post">
<div id="main-content">
<div class="container-fluid">
<!-- Page header section -->
<div class="block-header">
<div class="row clearfix">
<div class="col-lg-6 col-md-5 col-sm-12">
<h1>Hi, Welcomeback!</h1>
<span>You can edit banner here</span>
</div>
<div class="col-xl-6 col-md-7 col-sm-12 text-md-right">
<div class="d-flex align-items-center justify-content-md-end mt-4 mt-md-0 flex-wrap vivify pullUp delay-550">
<div class="mb-3 mb-xl-0 ">
<a asp-action="BannerDetails" class="btn btn-dark">Banner List</a>
</div>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-12">
<div class="card">
<div class="body">
<div class="header">
<h2><strong>Enter Banner Details</strong></h2>
</div>
<br />
<input asp-for="BannerId" type="hidden" />
<div class="row">
<div class="col-12">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" class="form-control" asp-for="BannerTitle" placeholder="Banner Title" aria-label="bannertitle" aria-describedby="basic-addon1">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group c_form_group">
<label>Banner Description</label>
<div class="input-group">
<textarea class="form-control" asp-for="BannerDescription" aria-label="Banner Description" rows="6"></textarea>
</div>
</div>
</div>
<div class="col-6">
<div class="drop-zone">
<span class="drop-zone__prompt">Drop file here or click to upload</span>
<input type="file" asp-for="BannerImg1" name="myFile" class="drop-zone__input" accept="image/*" data-allowed-file-extensions='["jpg", "png" , "jpeg"]' required>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" class="form-control" asp-for="BannerIndex" placeholder="Banner Index" aria-label="bannerindex" aria-describedby="basic-addon1">
</div>
</div>
</div>
<div class="col-6">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
</div>
</div>
</div>
</div>
<div class="mb-2" align="center">
<button type="submit" class="btn btn-success btn-round">Edit Banner</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
When i try To Edit the data in the browser it Throw exception, in database i have value but when i tried to fetch data its showing error.
thank you in advance to everybody for any help or advice.
According to the error message it is necessary to pass the BannerViewModels instance instead of the Banner entity:
public ActionResult EditBanner(int id)
{
var abd = _db.Banner.Where(a => a.BannerId == id)
.Select(b => new BannerViewModels()
{
BannerId = b.BannerId,
BannerTitle = b.BannerTitle,
BannerDescription = b.BannerDescription,
BannerImg = b.BannerImg,
BannerUrl = b.BannerUrl,
BannerIndex = b.BannerIndex,
BMasterId = b.BMasterId,
IsDeleted = b.IsDeleted
})
.FirstOrDefault();
return View(abd);
}
Passing an entity to the view as a data model is bad idea.
See the following post: Why it's not a good idea to pass entities as Models in MVC?

How to reference images from a diferent table C#

I have two tables, Libro (books) and Imagenes (Images) where Id on Libro is referenced on Imagenes as a fk on IdLibro so that I have an image for each Libro.
I want to reference the image on a Bootstrap card but they are on different tables on the database, how do I do it?
Here is what I have
#{
foreach (var lib in Model)
{
<div class="card col-md-3 m-2" style="width: 18rem;">
<img src="#Html.DisplayFor(modelItem => lib.Imagenes)" class="card-img-top" alt="There should be an image here">
<div class="card-body">
<h5 class="card-title">#lib.Titulo</h5>
#switch (lib.Saga)
{
case 0:
<h6> </h6>
break;
case 1:
<h6>Canción de Hielo y Fuego</h6>
break;
case 2:
<h6>Harry Potter</h6>
break;
}
<br />
<div class="row m-2">
<div class="col-md-12">
<p class="card-text">$#lib.Precio</p>
</div>
</div>
<br />
<div class="row m-2 position-absolute bottom-0">
<div class="col-md-4">
<a class="btn btn-outline-primary" href="/Home/Detalle/#lib.Id">Ver</a>
</div>
<div class="col-md-1"></div>
<div class="col-md-4">
<a onclick="Agregar(#lib.Id)" class="btn btn-outline-primary" id="#lib.Id">Agregar</a>
</div>
</div>
</div>
</div>
}
}
If the structure of your classes is as follows, you can easily access the Imagenes class values
public class Libro
{
public int Id { get; set; }
//........................
public ICollection<Imagenes> Imagenes { get; set; }
}
public class Imagenes
{
public int ID { get; set; }
//..............................
public int IdLibro { get; set; }
public Libro Libro { get; set; }
}
in view
#{
foreach (var lib in Model)
{
<img src="Url.Content(lib.Imagenes.FirstOrDefault().ImageUrl)" />
}
}

ASP.NET Razor Pages dropdown list from DB

I'm writing Application on ASP.NET Razor Pages(It's my homerwork).
Topic of this app is "Library" I have adding,deleting,modifying etc.
What i'm trying to do is. When i'm adding a new book, when it's genre of book i want to use dropdown list from database. I have been searching for this but i didn't find working solution for me.
So my Book class is:
Book.cs
public class Book
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Tytuł")]
public string Title { get; set; }
[Required]
[Display(Name = "Autor")]
public string Author { get; set; }
[Required]
[Display(Name = "Gatunek")]
public string Genre { get; set; }
[Required]
[Display(Name = "Rok Wydania")]
public int ReleaseYear { get; set; }
[Required]
[Display(Name = "Okładka")]
public string Cover { get; set; }
[Required]
[Display(Name = "Liczba Stron")]
public int NumberOfPages { get; set; }
[Required]
[Display(Name = "Opis")]
public string Description { get; set; }
}
Next i have Genre class
Genre.cs
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Gatunek")]
public string Name { get; set; }
I'm adding this to my ApplicationDbContext
ApplicationDbContext.cs
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Book> Book { get; set; }
public DbSet<Genre> Genre { get; set; }
AddBook.cshtml.cs
[Authorize(Roles = SD.AdminEndUser)]
public class AddBookModel : PageModel
{
private readonly ApplicationDbContext _db;
[BindProperty]
public Book Book { get; set; }
public AddBookModel(ApplicationDbContext db)
{
_db = db;
}
public IActionResult OnGet()
{
return Page();
}
public async Task <IActionResult> OnPostAsync(ServiceType ServiceType)
{
if(!ModelState.IsValid)
{
return Page();
}
_db.Book.Add(Book);
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
And
AddBook.cs
<form method="post">
<div class="border backgroundWhite">
<div class="form-group row">
<div class="col-2">
<label asp-for="Book.Title"></label>
</div>
<div class="col-5">
<input asp-for="Book.Title" class="form-control" />
</div>
<span asp-validation-for="Book.Title" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Book.Author"></label>
</div>
<div class="col-5">
<input asp-for="Book.Author" class="form-control" />
</div>
<span asp-validation-for="Book.Author" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Book.Genre"></label>
</div>
<div class="col-5">
<input asp-for="Book.Genre" class="form-control" />
</div>
<span asp-validation-for="Book.Genre" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Book.ReleaseYear"></label>
</div>
<div class="col-5">
<input asp-for="Book.ReleaseYear" class="form-control" />
</div>
<span asp-validation-for="Book.ReleaseYear" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Book.NumberOfPages"></label>
</div>
<div class="col-5">
<input asp-for="Book.NumberOfPages" class="form-control" />
</div>
<span asp-validation-for="Book.NumberOfPages" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Book.Cover"></label>
</div>
<div class="col-5">
<input asp-for="Book.Cover" class="form-control" />
</div>
<span asp-validation-for="Book.Cover" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Book.Description"></label>
</div>
<div class="col-5">
<input asp-for="Book.Description" class="form-control" />
</div>
<span asp-validation-for="Book.Description" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-5 offset-2">
<partial name="_AddAndBackToListButton" />
</div>
</div>
</div>
I have working connection with Db. I just don't know what i should do next to make dropdownlist. I'm not interested in solution with controllers!
Any ideas ?
Thank you for assistance!
This is a possible repeat of:
How to write a simple Html.DropDownListFor()? (Answered Jun 16 '10 )
But anyway, I'll try and answer:
If you're writing it in Razor syntax, you can just use the same solution as the link above. Create an HtmlDropdownFor, and as the argument perform a LINQ query on your List<Genre> (list of of genres, or dictionary of genres, whichever iterable you might need)
Otherwise, you can just manually write a <select></select> input inside each of the HTML form that requires it. Obviously this is more time-consuming, but you can find more info on how to do that, at w3 schools: HTML Form Elements, specifically the section about <select>

C# Razor Page Dynamically Create Divs with Attributes

I have the following CSHTML codes:
<div class="container-fluid projects padding-top-small">
<div class="row">
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="service1.html">
<img src="assets/img/portfolio/image1.jpg" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>Service 1</h3>
<p><small>Short Description 1</small></p>
</div>
</div>
</a>
</div>
</div>
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="service2.html">
<img src="assets/img/portfolio/image2.jpg" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>Service 2</h3>
<p><small>Short Description 2</small></p>
</div>
</div>
</a>
</div>
</div>
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="service1.html">
<img src="assets/img/portfolio/image3.jpg" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>Service 3</h3>
<p><small>Short Description 3</small></p>
</div>
</div>
</a>
</div>
</div>
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="service1.html">
<img src="assets/img/portfolio/image4.jpg" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>Service 4</h3>
<p><small>Short Description 4</small></p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
Pretty much everything is hard-coded HTML tags.
I want to be able to render them dynamically.
In my controller, I am retrieving a list of Service Object comprised of the following items: SERVICE_URL, SERVICE_IMAGE_URL, SERVICE_NAME and SERVICE_DESCRIPTION. These list is stored in the ViewBag (Not sure if the viewbag is the best placeholder).
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="SERVICE_URL">
<img src="SERVICE_IMAGE_URL" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>SERVICE_NAME</h3>
<p><small>SERVICE_DESCRIPTION</small></p>
</div>
</div>
</a>
</div>
</div>
What I want to achieve is to have each div rendered dynamically, so that I would be able to show up only those services available.
Controller.cs
public class myService
{
public string service_url { get; set; }
public string service_image_url { get; set; }
public string service_name { get; set; }
public string service_description { get; set; }
}
private void loadServices()
{
List<myService> myServices = new List<myService>();
for(int i=0; i<3; i++)
{
myService msvc = new myService();
msvc.service_url = "service_url" + i.ToString() + ".html";
msvc.service_image_url = "image_url" + i.ToString() + ".jpg";
msvc.service_name = "Service " + i.ToString();
msvc.service_description = "Service Description " + i.ToString();
myServices.Add(msvc);
}
ViewBag.DataServices = myServices;
}
public ActionResult Home()
{
loadServices();
return this.RedirectToAction("Index", "Controller");
}
Rephrasing the question:
Given on my Controller that I have a list of the services and storing them to the ViewBag, how do I generate the DIVs on the Razor Page with the attributes as provided from the hard coded HTML?
I built a working prototype of this and will run you through the steps of each part. I then suggest you find some good basic books on MVC Razor programming and start from the beginning as there is a lot of detail to learn:
Use separate files for any classes and put models in the models folder.
Use proper standards-based naming/proper-casing of properties (leading caps for properties & classes, "CamelCase" generally)
e.g. Models\MyService.cs:
namespace WebApplication.Models
{
public class MyService
{
public string ServiceUrl { get; set; }
public string ServiceImageUrl { get; set; }
public string ServiceName { get; set; }
public string ServiceDescription { get; set; }
}
}
Your Home controller wants a Services action so the the URL routing is from the meaningful /Home/Services
Controllers\HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication5.Models;
namespace WebApplication.Controllers
{
public class HomeController : Controller
{
private List<MyService> LoadServices()
{
List<MyService> myServices = new List<MyService>();
for (int i = 0; i < 3; i++)
{
MyService msvc = new MyService();
msvc.ServiceUrl = "service_url" + i.ToString() + ".html";
msvc.ServiceImageUrl = "image_url" + i.ToString() + ".jpg";
msvc.ServiceName = "Service " + i.ToString();
msvc.ServiceDescription = "Service Description " + i.ToString();
myServices.Add(msvc);
}
return myServices;
}
public ActionResult Services()
{
// return a view using the ViewModel provided by LoadServices()
return View(LoadServices());
}
}
}
In the view, you need to declare the type of View Model being passed
You need to loop over the Model (which is an enumerable collection)
Using Razor syntax you inject the properties of the Model's elements
Views\Home\Services.cshtml:
#model IEnumerable<WebApplication.Models.MyService>
<div class="container-fluid projects padding-top-small">
<div class="row">
#foreach (var service in Model)
{
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="#service.ServiceUrl">
<img src="#service.ServiceImageUrl" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>#service.ServiceName</h3>
<p><small>#service.ServiceDescription</small></p>
</div>
</div>
</a>
</div>
</div>
}
</div>
</div>
And the end result of all this work looks like this:

Categories

Resources