Multiple Views within Modal - c#

I am attempting to create a modal that has a tab menu, which allows you to switch between views. The reasonable approach seemed to do partial views and build the table using a for each statement; however, they're in different models so I am struggling. I've got the first view working in the modal, but i am unsure how to use different models in each view.
#model PortalDev.Models.ViewModels.EditUserViewModel
<div class="modal-body">
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="user-tab" data-toggle="tab" href="#user" role="tab" aria-controls="user" aria-selected="true">User</a>
</li>
<li class="nav-item">
<a class="nav-link" id="roles-tab" data-toggle="tab" href="#roles" role="tab" aria-controls="roles" aria-selected="false">Roles</a>
</li>
<li class="nav-item">
<a class="nav-link" id="claims-tab" data-toggle="tab" href="#claims" role="tab" aria-controls="claims" aria-selected="false">Claims</a>
</li>
</ul>
<div class="tab-content tabMenu" id="myTabContent">
#*----------------------Edit User Role Tab----------------------*#
<div class="tab-pane fade" id="roles" role="tabpanel" aria-labelledby="roles-tab">
<div class="wrapper">
<table class="table table-hover table-md ">
<thead>
<tr>
<td class="text-left TableHead">Id</td>
<td class="text-left TableHead">Role</td>
</tr>
</thead>
#*--Table Body For Each to pull DB records--*#
<tbody>
#foreach (var role in Model.Roles)
{
#Html.Partial("~/Views/Administration/Users/UserRoleTable.cshtml", role)
}
</tbody>
</table>
</div>
#*----------------------Edit User Claims Tab----------------------*#
<div class="tab-pane fade" id="claims" role="tabpanel" aria-labelledby="claims-tab">...</div>
</div>
</div>
</div>
------------------UserRoleTable.cshtml-------------------------------------
#model PortalDev.Models.ViewModels.ManageUserRoleViewModel
#{
ViewData["Title"] = "UserRoleTable";
}
<tr asp-action="ManageUserRoles" asp-controller="Administration" asp-route-id="#Model.RoleId">
<td class="text-left">#Model.RoleId</td>
<td class="text-left">#Model.RoleName</td>
</tr>
public class ManageUserRoleViewModel
{
public string RoleId { get; set; }
public string RoleName { get; set; }
public bool IsSelected { get; set; }
//Viewbag is used to store UserId
}
---------------EditUserVieModel.cs---------------
public class EditUserViewModel
{
public EditUserViewModel()
{
Claims = new List<string>(); Roles = new List<string>();
}
public string Id { get; set; }
[Required]
public string UserName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
public string City { get; set; }
public List<string> Claims { get; set; }
public IList<string> Roles { get; set; }
}
----------------AdministrationController.cs (method i need to call)----------
[HttpGet]
public async Task<IActionResult> ManageUserRoles(string userId)
{
ViewBag.userId = userId;
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {userId} cannot be found";
return View("NotFound");
}
var model = new List<ManageUserRoleViewModel>();
foreach (var role in roleManager.Roles)
{
var manageUserRoleViewModel = new ManageUserRoleViewModel
{
RoleId = role.Id,
RoleName = role.Name
};
if (await userManager.IsInRoleAsync(user, role.Name))
{
manageUserRoleViewModel.IsSelected = true;
}
else
{
manageUserRoleViewModel.IsSelected = false;
}
model.Add(manageUserRoleViewModel);
}
return View(model);
}
I have a users table... I want to be able to click on the user, get the edit modal to come up (works right now). Have 3 sub menu tabs on top. One for editing user info, Second for listing their Roles, Third for listing "claims".

You have a few options here. You could use TempData or ViewData dictionaries or your EditUserViewModel needs to contain all the models required to render the entire view along with any partial's it contains.
public class EditUserViewModel
{
public ModelClass1 Model1 { get; set; }
public ModelClass2 Model2 { get; set; }
}
Then you would pass these into the partial views.

Related

Iterate through a list in C# MVC and access properties

I have created a view that accepts a ProjectsCreatorsVM class. This class has been structured this way:
public class ProjectsCreatorsVM
{
public List<ProjectVM> ProjectsCreators { get; set; }
public ProjectsCreatorsVM(List<ProjectVM> projectsCreators)
{
ProjectsCreators = projectsCreators;
}
}
In addition, the ProjectVM follow this structure:
public class ProjectVM
{
public Project Project { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public ProjectVM(Project pro, ApplicationUser applUser)
{
Project = pro;
ApplicationUser = applUser;
}
}
Lastly, my view tries to go through the ProjectsCreators.Project but it does not seem to be possible.
<div class="card-content-container" >
#foreach (Project obj in #Model.ProjectsCreators.)
{
<div class="card">
<img class="card-img-top" src="#obj.ImgURL" alt ="project image" >
<div class="card-body d-flex flex-column">
<h5 class="card-title">#obj.Title</h5>
<h6 class="card-title">#obj.Title</h6>
<p class="card-text">
#obj.TruncatedDescription
</p>
<div class="mt-auto" style="display: flex; justify-content: space-between; align-items: center;">
View Details
</div>
</div>
</div>
I would appreciate any help. Thanks in advance.
ProjectCreators is a List and when you iterate ProjectCreators you get a ProjectVM object not a Project or ApplicaionUser instance. If you want to access Project instance add Project after #obj like #obj.Project.Title
<div class="card-content-container" >
#foreach (ProjectVM obj in #Model.ProjectsCreators.)
{
<div class="card">
<img class="card-img-top" src="#obj.Project.ImgURL" alt ="project image" >
<div class="card-body d-flex flex-column">
<h5 class="card-title">#obj.Project.Title</h5>
<h6 class="card-title">#obj.Project.Title</h6>
<p class="card-text">
#obj.Project.TruncatedDescription
</p>
<div class="mt-auto" style="display: flex; justify-content: space-between; align-items: center;">
View Details
</div>
</div>
</div>
}
</div>
To achieve what I wanted, I created another class. That looks like this:
public class ProjectAndUserVM
{
public string ProjectTitle { get; set; }
public string ProjectId { get; set; }
public string ProjectImageUrl { get; set; }
public string ProjectDescription { get; set; }
public string ProjectCreatorName { get; set; }
public string ProjectCreatorId { get; set; }
public string ProjectCreatorEmail { get; set; }
public ProjectAndUserVM(string projectTitle, string projectId, string projectImageUrl, string projectDescription, string projectCreatorName, string projectCreatorId, string projectCreatorEmail)
{
ProjectTitle = projectTitle;
ProjectId = projectId;
ProjectImageUrl = projectImageUrl;
ProjectDescription = projectDescription;
ProjectCreatorName = projectCreatorName;
ProjectCreatorId = projectCreatorId;
ProjectCreatorEmail = projectCreatorEmail;
}
}
So, basically my controller is returning that as a list which I convert to an IEnumerable. and I use that list on my view instead.

could not display image from database in one to many relation database

i was creating a two model for upload a multiple image.for that i have used one to many relationship database for imagelist.but this image's failed to show my browser.here is my code:
model
public class test
{
public string Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public List<Photo> Photos { get; set; }
}
//another model
public class Photo
{
public string PhotoId { get; set; }
public string Image { get; set; }
}
here i upload multiple image
Controller
[HttpPost]
public IActionResult Create(test product, IFormFile[] photos)
{
test t = new test();
if (photos == null || photos.Length == 0)
{
return Content("File(s) not selected");
}
else
{
product.Photos = new List<Photo>();
foreach (IFormFile photo in photos)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Images", photo.FileName);
var stream = new FileStream(path, FileMode.Create);
photo.CopyToAsync(stream);
//product.Photos.Add(photo.FileName);
product.Photos.Add(new Photo { Image = "Images/" + photo.FileName });
}
}
_db.test.Add(product);
_db.SaveChangesAsync();
return View();
}
this controller i used for display:
public IActionResult Index()
{
return View(_db.test.ToList());
}
here is the view of index.cshtml
<h1 class="text-center text-danger">Buy Now!!</h1>
<br /><br />
#using Practise.Models
#model List<test>
<div class="row">
#foreach (var laptop in Model)
{
<div class="col-4 ml-5">
<div class="card mb-4">
<div class="card-header">
<h4 class="my-4 font-weight-normal">
<label style="font-size:23px; color:black;text-align:center">#laptop.Name</label>
</h4>
</div>
<img src="~/#laptop.Photos" alt="Card Image" class="card-img-top" style="height:300px;" />
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<label style="font-size:20px;color:darkblue"><b>Price:#laptop.Price</b></label>
</div>
<a asp-action="Details" asp-controller="ShopShow" asp-route-id="#laptop.Id" class="btn btn-primary pull-right btn-outline-light">Details</a>
</div>
</div>
</div>
</div>
}
</div>
when i run the application.i could not find the expection output.that means, could not display image.
enter image description here
above output,i want to show here photo. what is the solution of this?
Assuming you need to show the first image only even if multiple images are present. Rewrite your img tag like below
#if(laptop.Photos!=null && laptop.Photos.Count!=0)
{
<img src="~/#laptop.Photos[0].Image" alt="Card Image" class="card-img-top" style="height:300px;" />
}

Asp.Net Core 2 - audio files from and to the database

I am currently creating a web application that is supposed to play sound files.
The first problem I have encountered is the fact that when writing audio files to a database, all records have the same value even though they are different audio files, database with audio files
I'm not sure if it saves it in a good way, but I wanted to do it in the same way as with pictures
Mp3 mp3 = new Mp3();
using (var memoryStream = new MemoryStream())
{
await createViewModel.Name_mp3.CopyToAsync(memoryStream);
mp3.Name_mp3 = memoryStream.ToArray();
}
_context.Mp3.Add(mp3);
_context.SaveChanges();
Please, give me a hint as to whether it should look like this
The second question is how to extract these audio files from the database. I also tried the way in which pictures were extracted from the database.
So my view looks like this
#model IEnumerable<inz.Models.Song>
#{
ViewData["Title"] = "Index";
}
<div class="panelDiv textColor">
<form asp-controller="Songs" asp-action="Index" method="get">
<div class="input-group w-50 m-4 mx-auto">
<input type="text" class="form-control input-lg border-danger searchBorder" placeholder="Wyszukaj utwór lub artyste" name="search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">
<i class="fas fa-search"></i>
</button>
</span>
<div class="dropdown w-0">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
<div class="dropdown-menu bg-danger" aria-labelledby="dropdownMenuButton">
<input type="submit" name="all" value="Wyświetl wszystko" class="btn btn-danger" />
</div>
</div>
</div>
</form>
<div class="text-center m-5">
<a asp-action=Create>
<buton class="textColor btnDiv">
Dodaj nowy utwór <i class="fas fa-plus-circle fa-lg"></i>
</buton>
</a>
</div>
#if (ViewBag.ShowList == true)
{
<div class="table-responsive">
<table class="table tableSong">
<thead class="bg-danger table-borderless">
<tr>
<th>
</th>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Album.Name_Album)
</th>
<th>
#Html.DisplayNameFor(model => model.Artist.Name_Artist)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<i class="fas fa-thumbs-up"></i>
<i class="fas fa-thumbs-down"></i>
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#if (item.Album.Name_Album != null)
{
<a asp-controller="Songs" asp-action="Album" asp-route-nameAlbum="#item.Album.Name_Album" class="link">#Html.DisplayFor(modelItem => item.Album.Name_Album)</a>
}
else
{
<span>Brak informacji</span>
}
</td>
<td>
<a asp-controller="Songs" asp-action="Artist" asp-route-name="#item.Artist.Name_Artist" class="link">#Html.DisplayFor(modelItem => item.Artist.Name_Artist)</a>
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.ID_Song">
<buton class="textColor btnIndex">Edytuj</buton>
</a>
<a asp-action="Details" asp-route-id="#item.ID_Song">
<buton class="textColor btnIndex">Detale</buton>
</a>
#if (User.IsInRole("Admin"))
{
<a asp-action="Delete" asp-route-id="#item.ID_Song">
<buton class="textColor btnIndex">Usuń</buton>
</a>
}
</td>
**<td>
#{
var base64 = Convert.ToBase64String(item.Mp3.Name_mp3);
var imgSrc = String.Format("data:audio/mp3;base64,{0}", base64);
}
<audio controls>
<source src="#imgSrc" type="audio/ogg" />
</audio>
</td>**
</tr>
}
</tbody>
</table>
</div>
}
else
{
<p class="mt-5"> Brak zawartości do wyświetlenia</p>
}
</div>
But I still have an error
I will add what my models look like
public class Mp3
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID_Mp3 { get; set; }
public byte[] Name_mp3 { get; set; }
}
and
public class CreateViewModel
{
public int ID_Song { get; set; }
[Required(ErrorMessage = "Proszę wpisać tytuł")]
[Display(Name = "Tytuł")]
public string Title { get; set; }
[Required(ErrorMessage = "Proszę wpisać nazwę artysty")]
[Display(Name = "Artysta")]
public string Name_Artist { get; set; }
[Display(Name = "Album")]
public string Name_Album { get; set; }
[Display(Name = "Producent")]
public string Name_Producer { get; set; }
public IFormFile Name_mp3 { get; set; }
}
I am asking for hints and I apologize for my English
I don't think that storing the audio files in the database it's a good idea.
You could instead save the file on disk, then save the path.
public class File
{
[Key]
public Guid Id { get; set; }
[Required]
public string Name{ get; set; }
[Required]
public string Path { get; set; }
[Required]
public DateTime Registered{ get; set; }
[Required]
public string RegisteredBy { get; set; }
public string Notes { get; set; }
}
To save the file:
using (var db = new EFModel())
{
if (file.Id == Guid.Empty)
{
file.Id = Guid.NewGuid();
db.Entry(file).State = EntityState.Added;
}
else
db.Entry(file).State = EntityState.Modified;
db.SaveChanges();
return archivo;
}
In the save button/action:
if (!fuArchivo.HasFile)
throw new UserException("Debes seleccionar un archivo.");
string nombreArchivo = Path.GetFileNameWithoutExtension(fuArchivo.FileName);
string extension = Path.GetExtension(fuArchivo.FileName);
string pathArchivo = Path.Combine(ConfigurationManager.AppSettings["rutaCarga"],
ae.IdTitulo.ToString(), ae.IdArchivoEtapa.ToString());
if (!Directory.Exists(pathArchivo))
Directory.CreateDirectory(pathArchivo);
pathArchivo = Path.Combine(pathArchivo, Guid.NewGuid().ToString() + extension);
fuArchivo.SaveAs(pathArchivo);
if (File.Exists(pathArchivo))
{
var archivo = new File()
{
Id = Guid.Empty,
RegisteredBy = ClaimsPrincipal.Current.Identity.Name,
Registered = DateTime.Now,
Name = nombreArchivo,
Path = pathArchivo
};
var on = new FileBO();
return on.Save(archivo);
}
else
throw new Exception("Se guardó el archivo pero no existe.");
Sorry, it's in spanish. Hope this helps.

How to get the View to return the ID via a ViewModel to the controller?

I currently have a view which returns an IEnumerable collection of Technicians via the TechnicianViewModel. The view model populates fine and displays the objects correctly.
However, at the moment I need someone to point me in the right direction with regards to selecting a specific technician.
If I was to click More Info on the technician, an [HttpGet] request would be initiated which would result in a queryString. And this is exactly what is against the requirements of this project.(Requirements of the project: no query string should appear in the URL)
Here is the view :-
#model IEnumerable<ActionAugerMVC.ViewModels.TechnicianViewModel>
<div class="row">
#foreach (var item in Model)
{
<div class="col-sm-6 col-md-3">
<div class="">
<div class="">
<div class="">
#item.UserName
</div>
<div class="">
Technician
</div>
</div>
<div class="">
<img src="~\imagesurl-#item.GenerateName()" class="img-responsive" alt="...">
</div>
<div class="">
<p class="overlay__desc">
#item.Bio
</p>
<ul class="overlay__social">
<li><i class="ion-social-twitter"></i></li>
<li><i class="ion-social-facebook"></i></li>
<li><i class="ion-social-skype"></i></li>
<li><i class="ion-social-whatsapp-outline"></i></li>
</ul>
More info
</div>
</div>
</div>
}
</div> <!-- / .row -->
Here is the View Model :-
public class TechnicianViewModel
{
public Guid ID { get; set; }
public string UserName { get; set; }
public string Bio { get; set; }
public string GenerateName()
{
string str = GenerateURL();
str = str + ".jpg";
return str;
}
public string GenerateURL()
{
string phrase = string.Format("{0}", UserName);
string str = phrase.ToLower();
str = Regex.Replace(str, #"\s", "-");
return str;
}
}
How can I avoid my controller method being an [HttpGet] as I had implemented here so that I can have the ID from the viewmodel object returned by the view.
[HttpGet]
[Route("technician/profile/calgary-{url}")]
public IActionResult Profile(Guid? ID,string url)
{
var Profile = unitOfWork.TechnicianRepository.GetByGuidId(ID);
return View(Profile);
}
In your View, change the link to the following:
More info
You can get rid of the HttpGet and Route decorators on your controller method. Those will be taken care of by the default routing config:
public ActionResult Profile(string id)
{
TempData["guid"] = id;
return RedirectToAction("Profile");
}
public ActionResult Profile()
{
Guid guid = Guid.Parse(TempData["guid"]);
var Profile = unitOfWork.TechnicianRepository.GetByGuidId(guid);
return View(Profile);
}

How can I retrieve values from the database from a specific users?

I want to be able to retrieve values from the database from a
specific user, which in this case #Model.user.Xp, it does not work, I
just get 0.
#model TheQuizR.Models.IndexViewModel
#using Microsoft.AspNet.Identity
<div class="row">
<div class="col-sm-6 col-md-6">
<ul class="list-group">
<div class="blue">
#User.Identity.GetUserName()<br />
</div>
<li class="list-group-item">
Title
<span class="badge">#Model.user.Xp</span>
</li>
<li class="list-group-item">
In the IndexViewModel I have this:
public class IndexViewModel
{
public ApplicationUser user = new ApplicationUser();
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
In the ApplicationUser class I have all the properties:
public class ApplicationUser : IdentityUser
{
[MaxLength(128)]
public string Title { get; set; }
[Range(0, 5000000)]
public int Xp { get; set; }
[Range(0, 100000)]
}
I cant get the id and the username thru Microsoft.AspNet.Identity (the one mark in yellow). I can't get all the other properties.
I would recommend to find the user in controller. Then you can create another model or use Viewbag.
string username = User.Identity.GetUserName();
var user = db.Users.First(u => u.UserAD == username);
ViewBag.userIDconnected = user.ID;
View -
<div class="row">
<div class="col-sm-6 col-md-6">
<ul class="list-group">
<div class="blue">
</div>
<li class="list-group-item">
Title
<span class="badge">#ViewBag.userIDconnected</span>
</li>
<li class="list-group-item">

Categories

Resources