Create a button in MVC to hide labels and replace it with '******' - c#

brief background, my application is a password manager and has a page where it displays labels,a services e.g. gmail and the password saved associated to it. I am trying to find a way to have a button or checkbox to show or hide the passwords so the user can see their passwords and then press a button to hide the passwords and mask them with a series of asterisks. I was hoping someone might have a jquery or razor idea to help em out?
<div class="panel-body">
<table class="table table-bordered table-responsive table-hover">
<tr>
<th>
#Html.DisplayNameFor(model => model.Website)
</th>
<th>
#Html.DisplayNameFor(model => model.Password)
</th>
<th>
#Html.DisplayNameFor(model => model.DateSaved)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Website)
</td>
<td>
#Html.DisplayFor(modelItem => item.Password)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateSaved)
</td>
<td>
#Html.ActionLink(" Edit", "Edit", new { id = item.Id }, new { #class = "btn btn-primary btn-sm glyphicon glyphicon-pencil" })
#Html.ActionLink(" Details", "Details", new { id = item.Id }, new { #class = "btn btn-info btn-sm glyphicon glyphicon-eye-open" })
#Html.ActionLink(" Delete", "Delete", new { id = item.Id }, new { #class = "btn btn-danger btn-sm glyphicon glyphicon-trash" })
#Html.ActionLink(" Strength Check", "Index", "StrengthCheck", new { id = item.Id }, new { #class = "btn btn-warning btn-sm" })
</td>
</tr>
}
</table>

You could use a simple JQuery function to toggle the field between asterisks and the real password value. The trick will be making sure each password field is uniquely identifiable so you only show that one password when you click the button (I'm assuming there will be multiple passwords on the screen since it's in a table)
Change the foreach loop to this so you have access to the index. This gives you easy access to a unique value for each row:
foreach (var item in Model.Select((value, i) => new { i, value }))
{
// You access the values like this now
var value = item.value;
var index = item.i;
}
See this answer for reference (the answer beneath the approved answer): How do you get the index of the current iteration of a foreach loop?
In the html table put:
<td>
<span id="password-#item.i" style="display: none;">#item.value.Password</span>
<span id="hidden-password-#item.i">*******</span>
<button onclick="showHidePassword('#item.i')">Toggle</button>
</td>
And somewhere on the page add the following javascript:
function showHidePassword(i) {
if ($('#password-' + i).is(':visible')) {
$('#password-' + i).hide();
$('#hidden-password-' + i).show();
} else {
$('#password-' + i).show();
$('#hidden-password-' + i).hide();
}
}
Hope this helps. To make reusability easier you could move this to a html extension method depending on how you're building out the rest of the page

Related

why Html.checkboxfor is not sends or changes the boolean value of the model?

I have a simple project that allows the customer to select multiple users and remove them from the DataBase. But the check boxes are not change or sent the isSelected variable which is tells the server that which users are have to be removed.
Client Side:
#model IEnumerable<WebApplication1.Models.User>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{
int i;
}
<h2><strong>جدول</strong></h2>
#using (Html.BeginForm())
{
<p>
#Html.ActionLink("اضافه کردن کاربر", "Create"
, null, new { #class = "btn btn-success", #id = "btnCreate" })
<input type="submit" class="btn btn-danger hidden" id="btnMultipleDelete" value="حذف کاربران" />
</p>
<table class="table" border="0" style="user-select: none;">
<tr>
<th>
<strong>نام</strong>
</th>
<th>
<strong>نام خانوادگی</strong>
</th>
<th>
<strong>سنّ</strong>
</th>
<th></th>
</tr>
#for(i = 0; i < Model.Count(); i++)
{
<tr class="mainList" id="tr-#i"
onmouseover="changeCurrentRow(this.id), mouseIn(true)"
onmouseout="clearCurrentRow(), mouseIn(false)">
<td class="IndexInfo">
<span class="IndexText">
#Html.DisplayFor(modelItem => modelItem.ToList()[i].User_FirstName)
</span>
</td>
<td class="IndexInfo">
<span class="IndexText">
#Html.DisplayFor(modelItem => modelItem.ToList()[i].User_LastName)
</span>
</td>
<td class="IndexInfo">
<span class="IndexText persianNumber">
#Html.DisplayFor(modelItem => modelItem.ToList()[i].User_Age)
</span>
</td>
<td align="center" style="flex:3">
#Html.ActionLink("ویرایش", "Edit", new { id = Model.ToList()[i].User_Id },
new { #class = "btn btn-primary", #id = "btnEdit-" + i })
#Html.ActionLink("مشاهده", "Details", new { id = Model.ToList()[i].User_Id },
new { #class = "btn btn-secondary", #id = "btnDetail-" + i })
#Html.ActionLink("حذف", "Delete", new { id = Model.ToList()[i].User_Id },
new { #class = "btn btn-warning", #id = "btnDelete-" + i })
#Html.HiddenFor(u => u.ToList()[i].User_Id)
#Html.HiddenFor(u => u.ToList()[i].User_FirstName)
#Html.HiddenFor(u => u.ToList()[i].User_LastName)
#Html.HiddenFor(u => u.ToList()[i].User_Age)
#Html.CheckBoxFor(u => u.ToList()[i].IsSelected, new { #class = "", #id = "cb-" + i })
</td>
</tr>
}
</table>
}
Server Side:
[HttpPost]
public ActionResult Index(IEnumerable<User> users)
{
if (users.Count() == 0)
{
return RedirectToAction("Index");
}
else
{
User user;
foreach (User u in users)
{
if (u.IsSelected)
{
user = db.Users.ToList().Find(x => x.User_Id == u.User_Id);
db.Users.Remove(user);
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
}
notice that i have tried to put a hidden input for isSelected Variable But that still doesn't work
so, while no one cares about my question i found the solution by my self.
Controller can not receive the IsSelected property from the View because i have changed the identity of the checkbox like id,name and ...
that means if i dont change the the identities of the checkbox, the code will works but even this solution leads us to another problem that you no longer can find the checkbox by JS. so i dont give this answer green tick until someone finds a better way to fix it.
for this solution something that you have to do is change the check box code from this:
#Html.CheckBoxFor(u => u.ToList()[i].IsSelected, new { #class = "", #id = "cb-" + i })
to this:
#Html.CheckBoxFor(u => u.ToList()[i].IsSelected})
and it basically will works.

Local variable in MVC View

I have an MVC view that displays a list of items. The table that was automatically generated with the view has this action link on every row:
#Html.ActionLink("Delete", "Delete", new { id = item.section_detail_id }).
This works fine but my requirement is to allow the user to highlight a row and click on a delete button at the bottom of the list. I need a way for the button to know which row is currently highlighted. So I created this local variable:
#{int sectionDetailId = 0; }
Then I added an onclick event on the table rows to store the the id of the row that is clicked:
tr id="#item.section_detail_id" onclick="addClass(this.id); sectionDetailId = #item.section_detail_id">
Here is the button that is supposed to bring up the delete view:
input type="button" value="Delete Employee" onclick="location.href='#Url.Action("Delete", "EmployeeList", new { id = sectionDetailId })'; alert(sectionDetailId)" />
The value that is passed to the view is always zero no matter what row is clicked. I added the alert function to the button to show that the variable has the correct value.
Is there a way to get the Action method to use the variable or to get the value from the table in some other way? The Action method works correctly if I hard code an ID.
Here is the complete view:
#model IEnumerable<VCPDS2.Models.EmployeeListViewModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<style>
tr.highlight {
background-color: blue !important;
}
</style>
#{int sectionDetailId = 0; }
<h2>Index</h2>
#*<p>
#Html.ActionLink("Create New", "Create")
</p>*#
#if (Model != null)
{
<table id="employeeTable" class="table table-responsive table-striped">
<tr>
<th>
Last Name
</th>
<th>
First Name
</th>
<th>
Employee ID
</th>
<th>
Phone
</th>
<th>
Budget Unit
</th>
<th>
Division
</th>
</tr>
<tbody id="employeeList">
#foreach (var item in Model)
{
<tr id="#item.section_detail_id" onclick="addClass(this.id); sectionDetailId = #item.section_detail_id">
<td>
#Html.DisplayFor(modelItem => item.last_name)
</td>
<td>
#Html.DisplayFor(modelItem => item.first_name)
</td>
<td>
#Html.DisplayFor(modelItem => item.employee_id)
</td>
<td>
#item.phone_nbr
#* #Html.DisplayFor(modelItem => item.phone.area_code) #Html.DisplayFor(modelItem => item.phone.phone_nbr)*#
</td>
<td>
#item.BU
#*#Html.DisplayFor(modelItem => item.phone.BU)*#
</td>
<td>
#item.description
#*#Html.DisplayFor(modelItem => item.department.description)*#
</td>
<td>
#*#Html.ActionLink("Edit", "Edit", new { id = item.section_detail_id }) |
#Html.ActionLink("Details", "Details", new { id = item.section_detail_id }) |*#
#Html.ActionLink("Delete", "Delete", new { id = item.section_detail_id })
</td>
</tr>
}
</tbody>
</table>
<p>
#*#Html.ActionLink("Create New", "Create")*#
<input type="button" value="Add Employee"
onclick="location.href='#Url.Action("Create", "EmployeeList")'" />
<input type="button" value="Delete Employee"
onclick="location.href='#Url.Action("Delete", "EmployeeList", new { id =
#sectionDetailId })'; alert(sectionDetailId)" />
</p>
}
<script src="jquery-3.4.1.min.js"></script>
<script>
function addClass(row) {
//alert(row);
$('#employeeList').children().removeClass('highlight');
var element = document.getElementById(row);
element.classList.add("highlight");
}
</script>
#*#Html.ActionLink("Edit", "Edit", new { id = item.section_detail_id }) |
#Html.ActionLink("Details", "Details", new { id = item.section_detail_id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.section_detail_id
})*#
This is the rendered HTML for the delete button:
<input type="button" value="Delete Employee" onclick="location.href='/EmployeeList/Delete/0'; alert(sectionDetailId)">

c# MVC Dynamically adding row to HTML Table but all fields in 1 cell

I am new to c# MVC and need some help. I am using Matt Lunn's example (http://www.mattlunn.me.uk/blog/2014/08/how-to-dynamically-via-ajax-add-new-items-to-a-bound-list-model-in-asp-mvc-net/) to dynamically add new items to a bound list in an HTML table. But instead of the new items getting added to each <td> they are all added in the first column <td> but I was them spread out in corresponding columns:
FY2017ACCOUNT ELEMENT345789POSITIONDirectorJOB TITLEDirector of Marketing
This is result all in first cell:
New FY box
New AccountElement box
New Position box
New Job Title box
But want this:
New FY Box in 1st cell | New Account Element box in 2nd cell | New Position box in 3rd cell | New Job Title Box in 4th cell
Here is my view:
<i>
<table>
<tr>
<th style="width:60px">FY</th>
<th style="width:230px">ACCOUNT ELEMENT</th>
<th align="center" style="width:50px">POSITION # <br />(IF APPLICABLE)</th>
<th style="width:230px">JOB TITLE</th>
<th style="width:250px">DEPT NAME</th>
<th style="width:230px">JUSTIFICATION FOR PT HOURS</th>
<th style="width:100px">HOURS <br />FOR YEAR</th>
<th style="width:200px">RATE</th>
<th style="width:200px">TOTAL <br />BUDGET</th>
</tr>
<tr id="pt-list">
#Html.EditorForMany(x => x.ptList, x => x.Index)
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
<td align="right">#String.Format("{0,14:c}", Model.ptList[0].total_total_budget)</td>
</tr>
</table>
<input type="button" id="add-pt" value="Add Part-Time" />
</i>
Script:
<i>
<script>
jQuery(document).ready(function ($) {
$('#add-pt').on('click', function () {
jQuery.get('/PCN/AddPT').done(function (html) {
$('#pt-list').append(html);
});
});
});
</script>
</i>
EditorTemplate:
<i>
#model Budget.Models.PCN.PCN_PT
<tr>
<td>
#Html.TextBoxFor(x => x.fy, new { #class = "form-controlsmaller" })
#Html.ValidationMessageFor(x => x.fy)
</td>
<td>
#Html.TextBoxFor(x => x.account_no, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.account_no)
</td>
<td>
#Html.TextBoxFor(x => x.position, new { #class = "form-controlsmaller" })
#Html.ValidationMessageFor(x => x.position)
</td>
<td>
#Html.TextBoxFor(x => x.job_title, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.job_title)
</td>
<td>
#Html.TextBoxFor(x => x.dept_name, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.dept_name)
</td>
<td>
#Html.TextBoxFor(x => x.justification, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.justification)
</td>
<td>
#Html.TextBoxFor(x => x.hrs_for_yr, "{0:0.00} ", new { #class = "form-controlsmaller" })
#Html.ValidationMessageFor(x => x.hrs_for_yr)
</td>
<td>
$#Html.TextBoxFor(x => x.rate, "{0:0.00} ", new { #class = "form-controlsmall" })
#Html.ValidationMessageFor(x => x.rate)
</td>
<td>
$#Html.TextBoxFor(x => x.total_budget, "{0:0.00} ", new { #class = "form-controltb" })
#Html.ValidationMessageFor(x => x.total_budget)
</td>
</tr>
</i>
PCN Controller to add New Row:
<i>
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AddPT()
{
var pt = new PCN();
pt.ptList.Add(new PCN.PCN_PT());
return View(pt);
}
</i>
How can I get the input fields displayed in the corresponding column of the table when I click Add Part-Time button? Any help would be greatly appreciated.
Take a close look what you are appending your information to.
<i>
<script>
jQuery(document).ready(function ($) {
$('#add-pt').on('click', function () {
jQuery.get('/PCN/AddPT').done(function (html) {
$('#pt-list').append(html);
});
});
});
</script>
</i>
and your html is:
<tr id="pt-list">
#Html.EditorForMany(x => x.ptList, x => x.Index)
</tr>
So you are appending the html to a TR element when you want to append something to the table.
use .after()
and insert a new tr and tds for your values.
And why is there a <i> in your template?
Remove that!
A row in a table cannot be italic!
Take a close look at how a table in html should look!
http://www.w3schools.com/html/html_tables.asp

DateTime destroys View

I have a pretty basic/standard MVC project I'm building up. Everything in it works fine (Fig 1) until I add a DateTime object to my Model (Fig 2), at which point the View for that Model gets very distorted, and won't display any information (Fig 3). See the entry in my SQL Database for the related DateTime object (Fig 4).
I am left to assume it's something to do specifically with the DateTime data type, but I'm not sure What might be causing this or what could I try for troubleshooting.
Fig 1:
Fig 2:
Fig 3:
Fig 4:
Code from my View as asked:
#model TKOPOC.Models.SubmitEIDs
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#* Model Update Alert *#
#if(Model.isVerify){ <h1><span style="color: red;">VERIFY YOUR CHANGES, THEN CLICK SUBMIT</span></h1> }
#*Search Box*#
#if(!Model.isVerify)
{
using (Html.BeginForm("Index", "EightID", FormMethod.Get))
{
<p>
Find by name or EID: #Html.TextBox("searchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
</p>
}
<p>
#Html.ActionLink("Create New", "Create")
</p>
}
<table>
<tr>
<th>
#Html.ActionLink("EID", "Index", new { sortOrder=ViewBag.EIDSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Name", "Index", new { sortOrder=ViewBag.NameSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Email", "Index", new { sortOrder=ViewBag.EmailSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Physical", "Index", new { sortOrder=ViewBag.PhysicalSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Admin", "Index", new { sortOrder=ViewBag.AdminSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink(" Maint", "Index", new { sortOrder=ViewBag.MaintSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink(" Cab", "Index", new { sortOrder=ViewBag.CabSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink(" Mills", "Index", new { sortOrder=ViewBag.MillSortParam, currentFilter=ViewBag.CurrentFilter })
</th>
<th></th>
</tr>
#foreach (var item in Model.EightIDsPagedList) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.EID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Physical)
</td>
<td>
#Html.DisplayFor(modelItem => item.Admin)
</td>
<td>
#Html.DisplayFor(modelItem => item.Maint)
</td>
<td>
#Html.DisplayFor(modelItem => item.Cab)
</td>
<td>
#if (item.Admin | item.Maint)
{
<text>All</text>
}
else
{
#Html.DisplayFor(modelItem => item.Mills.Count)
}
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.EightIDID }) |
#Html.ActionLink("Details", "Details", new { id=item.EightIDID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.EightIDID })
</td>
</tr>
}
</table>
<p>&nbsp</p>
#* Paging *#
<div>
Page #(Model.EightIDsPagedList.PageCount < Model.EightIDsPagedList.PageNumber ? 0 : Model.EightIDsPagedList.PageNumber)
of #Model.EightIDsPagedList.PageCount
#if (Model.EightIDsPagedList.HasPreviousPage)
{
#Html.ActionLink("<<", "Index", new { page = 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter })
#Html.Raw(" ");
#Html.ActionLink("< Prev", "Index", new { page = Model.EightIDsPagedList.PageNumber - 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter })
}
else
{
#:<<
#Html.Raw(" ");
#:< Prev
}
#for (var x = 1; x < Model.EightIDsPagedList.PageCount; x++)
{
if (Model.EightIDsPagedList.PageNumber == x)
{
#x;
}
else
{
#Html.ActionLink(Convert.ToString(x), "Index", new { page = x, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter });
}
}
#if (Model.EightIDsPagedList.HasNextPage)
{
#Html.ActionLink("Next >", "Index", new { page = Model.EightIDsPagedList.PageNumber + 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter })
#Html.Raw(" ");
#Html.ActionLink(">>", "Index", new { page = Model.EightIDsPagedList.PageCount, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter })
}
else
{
#:Next >
#Html.Raw(" ")
#:>>
}
</div>
<p>&nbsp</p>
<table border="0">
<tr>
#if (!Model.isVerify)
{
using (Html.BeginForm("Index", "EightID", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<td>
<input type="file" name="file" required />
<input type="submit" name="Verify" value="Verify" />
</td>
}
}
else
{
using (Html.BeginForm("Submit", "EightID", FormMethod.Post, new { NewEIDs = Model.EightIDs }))
{
<td>
<input type="submit" name="Submit Changes" value="Submit" />
</td>
}
using (Html.BeginForm("Cancel", "EightID", FormMethod.Post))
{
<td>
<input type="submit" name="Cancel" value="Cancel" />
</td>
}
}
</td>
</tr>
</table>
Edit:
After some more debugging through the view, I've found where the issue occurs, just not why - after the table headers, we come down to the foreach() loop where the DisplayFor happens. Here, the program hits foreach. Then Model.EightIDsPagedList. Then "in". But then it never comes into var or item and just skips the loop entirely. When I removed the DateTime items in question, the program enters the loop as you would expect it to and continues execution all the way down.
Do you get a null reference exception anywhere? Do you have a value in the DateTime column when you run the example? Your SQL seems to be nullable but your property is not. You could try these options:
Making that a DateTime? (nullable DateTime) in the code.
Make sure you have a value in SQL
Making the SQL column not nullable (which will guarantee option 2).
Let us know if that helps.

Why my button in MVC doesn't work?

I've got this code:
#model IEnumerable<PamelaFundacionFinal.Models.Escuela>
#{
ViewBag.Title = "Index";
}
<h2>Escuelas registradas</h2>
<p>
<button name="Edit" class="btn btn-default"><b>
#Html.ActionLink("Create New", "Create")</b></button></p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Nombre)
</th>
<th>
#Html.DisplayNameFor(model => model.Direccion)
</th>
<th>
#Html.DisplayNameFor(model => model.Telefono)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Nombre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Direccion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Telefono)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Escuela_ID })
<button name="Edit" class="btn btn-default">
#Html.ActionLink("Details", "Details", new { id = item.Escuela_ID })</button>
<button name="Edit" class="btn btn-default">
#Html.ActionLink("Delete", "Delete", new { id = item.Escuela_ID })</button>
</td>
</tr>
}
</table>
Don't worry, everything is referenced to their own controller to make the opperations, my issue is that I've got two cases:
I'm writing in #Html.ActionLink("Edit", "Edit", new { id = item.Escuela_ID }) a reference to another controller, so I can create a new one, but it's simple text
Then, I'm trying to put that reference into a button, so it looks nice: <button name="Edit" class="btn btn-default">#Html.ActionLink("Delete", "Delete", new { id = item.Escuela_ID })</button> but it doesn't work.
I know that I'm not writing this correctly, but I need help because I'm new with this language and I don't really know exactly how is the syntax. I'm using Visual Studio 2013 and SQL Server to run the database (The connection with database is running perfectly, it's not an issue with the database).
You can style your <a> tag that is generated by the Html helper.
#Html.ActionLink("Edit", "Edit", new { id = item.Escuela_ID },
new { #class = "btn btn-default" })

Categories