manage account mvc app c# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to get my ‘manage’ link to redirect to the relevant account.
I have a BankAccsController which works for fine for viewing details for a logged in user and to see both accounts held in the database, but what I want to do is be able to click the corresponding button to the right of the account and for it to take me to the details for that specific account. I know I will have to create a new method to replace the current two ‘ViewCurrent and ViewSavings’ and use parameters but I’m unsure how to do it and can’t find the correct words to type it into Google.
Controller
//View all accounts of logged in user
[Authorize]
public ActionResult Index()
{
var userId = User.Identity.GetUserId();
var bankAccs = db.BankAccs.Where(a => a.AccUserId == userId).ToList();
return View(bankAccs.ToList());
}
////View current account of logged in user
public ActionResult ViewCurrent()
{
var userId = User.Identity.GetUserId();
ViewModels.CurrentAccVm bankVm = new ViewModels.CurrentAccVm();
bankVm.BankAccList = db.BankAccs.Where(a => a.AccUserId == userId && a.AccTypeId == 1).ToList();
bankVm.UserName = User.Identity.GetUserName();
return View(bankVm);
}
////View Savings account of logged in user
public ActionResult ViewSavings()
{
var userId = User.Identity.GetUserId();
ViewModels.CurrentAccVm bankVm = new ViewModels.CurrentAccVm();
bankVm.BankAccList = db.BankAccs.Where(a => a.AccUserId == userId && a.AccTypeId == 2).ToList();
bankVm.UserName = User.Identity.GetUserName();
return View(bankVm);
}
View
#model IEnumerable<Atm11.Models.BankAcc>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Balance)
</th>
<th>
#Html.DisplayNameFor(model => model.AccType.AccountType)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Balance)
</td>
<td>
#Html.DisplayFor(modelItem => item.AccType.AccountType)
</td>
<td>
#Html.ActionLink("Manage", "ViewAccounts", new { id = item.Id })
</td>
</tr>
}
</table>

You are so close! Add the below method to your controller. Your view is constructed correctly so no changes are needed to that file.
Controller
public ActionResult ViewAccounts(int id)
{
var myAccount = DB.Accounts.GetByID(id);
return View(myAccount);
}
Next, you will need to create a ViewAccounts view.

Related

ASP.NET Core 5 MVC Render string from action in view

I try to display a string from Action in a View. This sounds like a very simple and easy task, but I don't get it how to do this.
My async Action returns Content Result:
public async Task<IActionResult> DisplayName(string key)
{
// Retrieves the requested culture
var rqf = Request.HttpContext.Features.Get<IRequestCultureFeature>();
// Culture contains the information of the requested culture
var culture = rqf.RequestCulture.Culture;
return Content(await Task.FromResult(_displayProvider.GetDisplayName(key, culture.Name)));
}
My View is very simple html:
#model List<MyModel>
<table class="table table-bordered table-striped datatable">
<thead class="table-head-dark">
<tr>
<th>
#Html.DisplayNameFor(model => model.First().Id)
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
<partial name="_EditDetailButton" model="#item.Id" />
<partial name="_DeleteButton" model="#item" />
</td>
</tr>
}
</tbody>
</table>
Instead of #Html.DisplayNameFor(model => model.First().Id) I want to Display a user-defined value. The user-defined value is returned from the Action.
I tried #Url.Action("DisplayName", "DisplayName", new { key = "MyModel.Id" }) but this is rendering an Url.
I tried Html.RenderAction("DisplayName", "DisplayName", new { key = "LastName" }) but RenderAction does not exist in ASP.NET Core 5.
I could call a static Class e. g. DisplayNameProvider.GetDisplayName("MyModel.Id", ???) but i dont know how to get the choosen culture to pass it to the method.
How do I get this working? I am also not familiar with components in ASP.NET Core.
Or is there a completely different solution for displaying strings, which the user has defined and save to the database? The DisplayNameProvider is retrieving the strings from database and handles caching.
UPDATE:
The Goal is to store and change displaynames for properties in the database. The user can change the displaynames. In my example the user wants a different displayname for the column header. I cannot use resource files as these are static and cannot be changed during runtime.
This is my DisplayNameProvider.GetDisplayName Method:
public string GetDisplayName(string ressourceKey, string language)
{
var ressources = GetCached(language);
var item = ressources.FirstOrDefault(r => r.ResourceKey == ressourceKey);
return item.Text;
}
Thanks in advance
I ended up using a string localizer, which returns the desired value for my properties.
Now i can use displaynamefor and it shows the value of the language. E.g.:
#Html.DisplayNameFor(model => model.MyProperty)

List View / Details View without Entity Framework

I have a MVC view that has a table that contains a list of all users within a specific OU within Active Directory. I am trying to add a column to the table that takes you to a Details view that shows the details of the user (shows additional details) but I am having a hard time figuring out how to do this without using Entity Framework and passing the id of the object to the details view. Any thoughts on how I could accomplish this? Right now when I click on the Details actionlink, I am taken to the Details view but there is no data being passed. Any help would be greatly appreciated!
public ActionResult NonComputerUsers(User model)
{
List<User> user = new List<User>();
using (var context = new PrincipalContext(ContextType.Domain, "XXX", "OU=XXX,DC=XXX,DC=com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry entry = result.GetUnderlyingObject() as DirectoryEntry;
user.Add(new User()
{
FirstName = (String)entry.Properties["givenName"].Value,
LastName = (String)entry.Properties["sn"].Value,
});
}
}
}
return View(user.ToList());
}
public ActionResult Details(User model)
{
?????????
return View(model);
}
**List View**
#model ADUserManagement.Models.User
<table class="table">
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.ActionLink("Details", "Details", "Users", new { item = item.FirstName })
</td>
</tr>
}
**Details View**
#model ADUserManagement.Models.User
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<table class="table table-bordered table-striped">
<tr>
<td>First Name</td>
<td>#Model.FirstName</td>
</tr>
<tr>
<td>Last Name</td>
<td>#Model.LastName</td>
</tr>
<tr>
<td>SAM Account Name</td>
<td>#Model.SamAccountName</td>
</tr>
There are a couple ways to do this. One of which is the way you are already doing it. You can add all the properties you want to display on your details page to your User model. Use that list to build your table, then pass the applicable User object back to your Details view to display the extra details.
That method is good because it saves you having to do a second lookup to AD for your Details view (essentially, your ????????? can be removed - you don't need any code there).
I was going to say that the down side is that, in your search, you're asking for more details for most of the accounts than you'd actually use, but the UserPrincipal objects that PrincipalSearcher returns already pulls in all the AD attributes for each user account anyway. If you used DirectorySearcher directly, you'd have more control of that. But that's probably not a big deal, unless you have performance problems with that search.
The other way to do it, which I think is unnecessary in your current example, is to store some unique identifier from AD (e.g. distinguishedName, sAMAccountName, userPrincipalName, objectGuid, objectSid) and pass just that back to your Details action where you can look up just that account again and get all the details you need for your Details view.

String with email format turns into Hyperlink

Hi this probably is an easy question but i cant find information about how to solve it i have a table with a field named Email and the values are of type string but the problem is that mvc or the browser automatically changes that string email into Hyperlink as shown in the following picture
when i inspect the element it is an hyperlink:
lacubana#la.com
what can i do to only display the emails as string? i don't want that information to be in hyperlink format. thanks very much
Edited: here is my code of the view
<table class="table table-bordered table-striped">
<tr>
<th>Email</th>
<th>Contraseña</th>
<th>NickName</th>
<th>TipoUsuario</th>
<th>Acciones</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Email)</td>
<td>#Html.DisplayFor(modelItem => item.Contraseña)</td>
<td>#Html.DisplayFor(modelItem => item.NickName)</td>
#if (item.TipoUsuario == 1)
{
<td>Administrador</td>
}
else
{
<td>Vendedor</td>
}
<td>
#Html.ActionLink("Editar", "EditarUsuario", new { id = item.IdUser }) |
#Html.ActionLink("Eliminar", "EliminarUsuario", new { id = item.IdUser })
</td>
</tr>
}
</table>
and here is the code of my controller:
IList<Usuario> UsuarioList = new List<Usuario>();
var query = from usu in database.ReportingUsersT
where usu.Activo == 1
select usu;
var listdata = query.ToList();
foreach (var Usuariodata in listdata)
{
UsuarioList.Add(new Usuario()
{
IdUser = Usuariodata.IdUser,
Email = Usuariodata.Email,
Contraseña = Usuariodata.Contraseña,
NickName = Usuariodata.NickName,
TipoUsuario = Usuariodata.TipoUsuario
});
}
return View(UsuarioList);
#Html.DisplayFor(...) is determining that the text is an email and is wrapping it in a link. You can simply use
<td>#item.Email</td>
to display it as text

Update Values in Database - MVC

im using the sortable jquery plugin, because i want that the user can choice the order of the images are showing in my view.
For this i have a Get Controller which sends the data to my PartialView.
How can i make the now the Post Controller to update my table in my database?
Note: In this moment the controller don´t receive any data. i haven´t figured out what is wrong
Someone can help me with this?
Thanks in advance:
Here is my code:
In My PartialView:
#(Html.BeginForm("UpdateOrder", "Admin", FormMethod.Post)){
<div id="Order">
<ul id="sortable">
#foreach (var p in ViewBag.Images)
{
<li id="#Html.AttributeEncode(p.FileName)">
<img src="~/Files/#p.FileName"/>
</li>
}
</ul>
</div>
}
Controller:
if (ModelState.IsValid)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append("Update Image Set MyFileName=??? Order By ASC");
cn.Open();
cmd = new SqlCommand(sql.ToString(), cn);
cmd.Parameters.Add(??????????).Value = ;
cmd.ExecuteNonQuery();
cn.Close();
}
}
return View();
Are you looking for something like this?
SqlCommand comm = new SqlCommand("UPDATE Customers SET Name=#name WHERE ID=#id", con;
comm.Parameters.AddWithValue("#name", "John");
comm.Parameters.AddWithValue("#id", id);
For passing data from view to controller take a look at the following links: ASP.NET MVC 3 Razor: Passing Data from View to Controller
ASP.Net MVC Passing multiple parameters to a view
I have created a backend for a website, where i e.g. can add, edit, delete events. So the snippet in the view for the events looks like this:
<div id="tabs-2" class="ui-widget-content">
<h2>
Events</h2>
<p>
#Html.ActionLink("Create new Event", "EventCreate")
</p>
<table id="tableEvent">
<tr>
<th>
Event
</th>
<th>
Date
</th>
<th>
Day of the Week
</th>
<th>
</th>
</tr>
#foreach (var e in ViewBag.Events)
{
<tr id="#e.EventID">
<td>
<h4>#e.EventName</h4>
</td>
<td>
<h4>#string.Format("{0:d}", e.Datum)</h4>
</td>
<td>
<h4>#e.Tag</h4>
</td>
<td>
#Html.ActionLink("Löschen", "EventDelete", new { id = e.EventID })
</td>
</tr>
}
</table>
</div>
I pass the id to the controller in the ActionLink and call the EventDelete:
[Authorize]
public ActionResult EventDelete(int id)
{
repevent.Delete(id);
return RedirectToAction("Main");
}
Now i have the id of the event and can do whatever i want. (In my case, i delete the event with the associated id.
public void Delete(int id)
{
using (KiGaDBEntities db = new KiGaDBEntities())
{
Event event = db.Event.SingleOrDefault(e => e.EventID == id);
if (event != null)
{
db.Event.Remove(event);
db.SaveChanges();
}
}
}
I hope that helps you!

Updating Multiple Records in one view; "Not all code paths return a value" error

I'm really new to programming and stuck on a problem.
I'm trying to edit and update multiple rows of a database in one view, using mvc and asp.net.
I think I'm somewhere along the right tracks but keep getting an error saying "not all code paths return a value".
My Conroller looks like this:
[HttpGet]
public ViewResult AnotherListEdit()
{
var chosenClass = from c in db.ClassInstanceDetails.Include("ClassInstance").Include("Student")
where c.ClassInstance.ID == 1
select c;
return View(chosenClass.ToList());
}
[HttpPost]
public ActionResult AnotherListEdit(IList<ClassInstanceDetail> list)
{
if (ModelState.IsValid)
{
foreach (ClassInstanceDetail editedClassInstanceDetail in list)
{
var tempBook = (from classInstDet in db.ClassInstanceDetails
where (teacher.ClassInstanceID == editedClassInstanceDetail.ClassInstanceID)
&& (classInstDet.StudentID == editedClassInstanceDetail.StudentID)
select teacher).First();
db.ApplyCurrentValues(tempBook.EntityKey.EntitySetName, editedClassInstanceDetail);
}
db.SaveChanges();
return View(db.Teachers.ToList());
}
}
My View looks like this:
#model IList<FYPSchoolApp.DAL.ClassInstanceDetail>
#{
ViewBag.Title = "AnotherListEdit";
}
#using (Html.BeginForm())
{
<table>
<tr>
<th>
Name
</th>
<th>
Second Name
</th>
<th>
attendance
</th>
<th>
Comment
</th>
</tr>
#for (var i = 0; i < Model.Count(); i++) {
<tr>
<td>
#Html.DisplayFor(m => Model[i].StudentID)
</td>
<td>
#Html.DisplayFor(m => Model[i].Attendance)
#Html.EditorFor(m => Model[i].Attendance)
</td>
<td>
#Html.DisplayFor(m => Model[i].CommentNote)
#Html.EditorFor(m => Model[i].CommentNote)
</td>
</tr>
}
</table>
<input type="submit" value="save" />
}
The "not all code paths return a value error" is being highlighted with AnotherListEdit function, the second one thats after HttpPost. If I run the project without that whole function, the display works, and the correct information is passed to the display.
Any help would be very much appreciated!!
What should happen in the AnotherListEdit method if the modelstate is invalid? That is what is missing ... The action does not return a "ActionResult" if the modelstate is invalid
[HttpPost]
public ActionResult AnotherListEdit(IList<ClassInstanceDetail> list)
{
if (ModelState.IsValid)
{
foreach (ClassInstanceDetail editedClassInstanceDetail in list)
{
var tempBook = (from teacher in db.ClassInstanceDetails
where (teacher.ClassInstanceID == editedClassInstanceDetail.ClassInstanceID)
&& (teacher.StudentID == editedClassInstanceDetail.StudentID)
select teacher).First();
db.ApplyCurrentValues(tempBook.EntityKey.EntitySetName, editedClassInstanceDetail);
}
db.SaveChanges();
return View(db.Teachers.ToList());
}
//HERE!!What view should return? any error messages?
return View("View with no valid modelstate?");
//Maybe?
//return RedirectToAction("AnotherListEdit");
}
if (ModelState.IsValid)
{ //you return something here }
but if the modelstate is not valid, nothing is returned. The error must come from there

Categories