Adding check boxes to allow multiple Delete & edit from my html table - javascript

I have the following table inside my asp.net mvc view:-
#foreach (var item in Model) {
<tr id="#item.TMSServerID">
<td>
#Html.ActionLink("Edit", "Edit","Server", new { id=item.TMSServerID },null) |
#if (!item.IsAlreadyAssigned()){
#Ajax.ActionLink("Delete",
"Delete", "Server",
new { id = item.TMSServerID },
new AjaxOptions
{ Confirm = "Are You sure You want to delete (" + item.Technology.Tag.ToString() + ")",
HttpMethod = "Post",
OnSuccess = "deletionconfirmation",
OnFailure = "deletionerror"
})}
</td>
<td>
#Html.ActionLink(item.Technology.Tag,"Details","Server",new { id = item.TMSServerID},null)
</td>
<td class="hidden-phone" >
#item.status
</td>
The table allow edit,delete single item at a time. But now I want to do the following:-
Add a checkbox beside each row.
Add a Ajax delete button to delete selected items
Add a Transfer ajax button, which allow editing the selected items status.
So I am trying to achieve the following:-
How can I pass the item id + item timestamp field , using ajax button , as I need to check if the selected items has been modified by another user?
How I can remove the selected row from the html table incase the delete operation successed ?
Thanks

add a check box on each first cell of the table with ModelID as the value of each checkbox.
inside your foreach, include this:
<td>
<input type="checkbox" name="TMSServerID" value="1" />
</td>
add this into tha parameter of your controller: Int32[] idList, something like this:
public void CheckForIds(Int32[] idList)
{
//Manipulate idList
}
and in your button event, call the controller method.
You might want to take a look at this for your reference:
http://byatool.com/mvc/asp-net-mvc-how-to-handle-multiple-checkboxes-with-viewsactions-jquery-too/

Related

Add a link in last column of specific row, after last span, using jquery

I have a drop-down for change state in each row of my table. This drop-down will change the state of current row by Ajax call. If the new state is not done or cancel, we should see the Edit link in last column of current row, after other links.
$(".state-select-container").change(function () {
var id = $(this).attr("data-id");
var state = $(this).val();
var url = "/MyController/ChangeState?requestId=" + id + "&state=" + state;
var that = $(this);
$.post(url, function (data) {
if (data.updated) {
//some other codes
if (state !== 'Cancel' && state !== 'Done') { //Edit is authorized
var href = '/MyController/Edit?requestId='+ id +'"';
//WHAT IS THE CORRECT CODE HERE? THE CODE, BELOW,
//ADDS THE LINK AFTER THE CURRENT ROW, NOT IN LAST COLUMN, AFTER LAST SPAN
that.closest("tr").last('td').last('span')
.after('Edit');
}
} else {
alert("Error!");
}
});
});
and the .cshtml is:
<table>
foreach (var item in ViewBag.SearchResult)
{
<tr>
<td>
<div>
<select class="state-select-container" data-id="#item.Id">
#{
foreach (var state in states)
{
<option value="#state.Value"
#(item.State[0].ToString()==state.Value ?"selected":"")>
#state.Text
</option>
}
}
</select>
</div>
</td>
<td>
<span>
<a data-id="#item.Id" href='its href' data-toggle="tooltip"></a>
</span>
#if (item.IsEditAuthorized)
{
<a href='#Url.Action("Edit", "MyController", new {requestId = #item.Id}, null)'>Edit</a>
}
</td>
</tr>
}
</table>
use like this
that.closest("tr").find('td:last-child').find('span:last-chi‌​ld').after('Edit');
Read Documentation last()
Note : last() This method does not accept any arguments.
Try below code
that.closest("tr").last().append('Edit');
Give this code a try,
that.closest("tr").children('td:last').children('span:last').after('Edit');
Your js code seems ok, but your HTML code is ba, perhaps you close the first anchor tag:
<a data-id="#item.Id" href='its href' data-toggle="tooltip"></a>
EDIT:
Ok, the html code is ok, but last() jquery function doesn't accept arguments (https://api.jquery.com/last/). So the comment of JYoThI is correct, or using last function:
$(this).closest("tr").find('td').last().find('span').last()

Child Div is not removed when tried to remove using Jquery

Clearing child div inside parent div, there are many answers like :
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
Probably I have listed all possible way to remove the div's, but even after using all these, I still not able to clear all the div's inside Parent Div. let me explain what I am doing and what I need.
Scenario :
I have two container-1, one of the container has input search box, where I can search for entering employee name and select few employees Ex. 5 and can use "Add" button to move those employees to the other container-2 which is 'div'.
Now I click on report button event and get the information of those 5 people in different aspx, now if i go back to the page where i have to search for another 3 employees and when I again click on the "Add" button, it should add only 3 employees instead it is adding last searched 5 + 3 employees!!.
So i am trying to clear the 5 employees inside that div after i click on "Report" button , when i use alert() it says it has 0 element, but when I add it for the second time, it appends the data again, which i dont need. here is the code :
Points to remember :
1. ParentDiv is the container-2
2. ChildDiv is the child div inside ParentDiv(which is dynamically appended when we select 5 employees on "Add" button click"
Here is the code:
HTML :
<table id="topTable">
<tr>
<td id="leftpane">
<h4>Search for Employee by Name or Profile:</h4>
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
<select id="EmployeeList" size="20" multiple></select>
</td>
<td id="centerpane">
<div> <input type="button" value="Add >>" class="AddButton" id="buttonAdd" /></div>
<div> <input type="button" value="Add All >>" class="AddButton" id="buttonAddAll" /></div>
</td>
<td id="rightpane">
<h4>Selected Employees:</h4>
<div id="ParentDiv"></div>
</td>
</tr>
</table>
Run Report button event
<input class="data" type="submit" name="cmdSubmit" value="Run Report" onclick="return FormValidate();"
onserverclick="RunReport" runat="server" id="Submit1" />
Add Button Click :
which moves the employees from container-1 to container-2.
$(document).on('click', '#buttonAdd', function (e) {
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
var myNode = $("#ParentDiv")[0];
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
On click of "Report" button it should clear all the elements from ParentDiv/ChildDiv which is what I did, but still it is not clearing it, how can I resolve/remove these elements once "Report" button event clicked.
Here is a sample of "Report" button event :
function FormValidate() {//Part of my other code
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
}
None of them is working, i feel there is an issue with the "Add" button event, where it is storing the data.
NOTE :
I don't want to clear the array of employee list, since I want to select multiple employees again again Ex. I can select 2 employees starts with the letter "M" and I can search the 2 employees of letter "L" and add those 2 employees, the container should hold 4 employees before "Report" button click.
Let me know if I am clear enough.
Console Log
Finally I could able to fix the issue, i was facing, I am posting the answer, now it is working as I need.
$(document).on('click', '#buttonAdd', function (e) {
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = []; // Clearing the hash, so that it can add fresh employees, if count == 0 in container- 2.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
else { // If there are existing employees in container-2 then append few more.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
var myNode = $("#ParentDiv")[0];
console.log(myNode);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
What I did
Since I should be able to append multiple employees by searching, that is handled in 'else' part, if I generated the "Report" then, I am clearing the Container-2.
When I come back to page to search few more employees, by this time Container-2 will not be having any employees, so
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = [];
//....
}
will clear the array which allow me to add fresh employees, hence it solved my problem :)
Thanks all for the support.
Edited to adjust on comments:
You need to clear the myHash variable. Otherwise employees will be added again from there.

CheckBox in Asp.Net MVC 4

I have checkbox. When I select the checkbox I want it to automatically change its value in the Database to true and refresh the view and invoke a JQuery method.
I also have a checkbox and label. I want the checkbox to disappear when selected and the text in the label to change.
<h2>Tasks</h2>
<fieldset>
<legend>Tasks</legend>
<table class="table">
#foreach(var item in ViewBag.x)
{
<tr class="clr">
<td style="width:520px">
#item.User.UserName
</td>
<td>
#item.date.ToString("MM/dd/yyyy")
</td>
</tr>
<tr class="clr">
<td>
#item.Discription
</td>
<td></td>
</tr>
<tr>
<td ></td>
<td>
<div><input type="checkbox" id="ch" class="ch" /><span id="d" >Done</span></div>
</td>
</tr>
}
How would I do this in JQuery or ASP MVC?
Image example
You can listen to the change event on the check box and then make an ajax call to your server to make updates to your db and have your action method return a response. You can check this response and hide/show whatever you want.
You probably want to associate the user id with the checkbox because you need to make this update against a specific user.. You may keep the user id in html 5 data attributes in the check box. Also looks like you are hard coding the id value of checkbox and the span in the loop, which will produce the same value for multiple checkboxes. Id values should be unique. So let's remove the id property value from your markup since we are not using it now.
<div>
<input type="checkbox" data-user="#item.UserId" class="ch" />
<span class="msg">Done</span>
</div>
And your javascript code will be
$(function(){
$("input.ch").change(function(e){
var _this=$(this);
var userId=_this.data("user");
var isChecked=_this.prop("checked");
$.post("#Url.Action("Change","Home")", { isChecked :isChecked, userId:userId },
function(re){
if(re.status==="success")
{
_this.closest("div").find("span.msg").html(re.message); //update span content
_this.remove(); // remove checkbox
}
else
{
alert("Failed to update!");
}
});
});
});
I am using Url.Action helper method to generate the relative url to the action method. This code will work if you include your script inside the razor view, but if your javascript code is in an external js file, you should build the path to the app root and pass that to your external js files via some variables as explained in this answer.
Assuming you have a Change action method in your HomeController which accepts the isChecked value
[HttpPost]
public ActionResult Change(int userId, bool isChecked)
{
try
{
// to do: using userId and isChecked param value, update your db
return Json( new { status="success", message="done"});
}
catch(Exception ex)
{
//to do : Log ex
return Json( new { status="error", message="Error updating!"});
}
}

How to populate a different View on redirect and trigger button submit

I'm using MVC/ASP.NET
I have two views, one displays a list of items based on a group ID. the other page displays various pieces of information which is generated from multiple options. which options the user can enter are determined from a dropdown select.
View1.aspx
<input type="button"
value="View All Details%>"
class="button"
onclick="window.location = '<%:Url.Action("Index", "Report", new { id = Model.GroupID})%>'" />
I am able to successfully change to the indicated page and the page's controller get's called. Model.GroupID is the value I need to submit the new form with.
Q1: How can I trigger the dropdown box to go to the desired selected index and then populate the textbox with the value from `Model.GroupID'?
Index.aspx
...
<% using (Html.BeginForm("Report", "Report", FormMethod.Post, new { id = "some" }))
{
....
<%: Html.TextBoxFor(model => model.textBox.input, new { id = "textboxID", style = "width:" + Model.textBox.width + "px", maxlength = Model.textBox.maxLength })%>
<input type="submit" name="button" value="Find Details" style="width: 180px" />
}
I need to then submit the form, which will call my controller
Controller.cs
[Authorize]
[HttpPost]
public ActionResult Report([Bind(Include = "textBox")]Report values)
{
....
}
Q is there a way to call the directly from the different view? I don't mind creating a seperate method in the controller either to avoid binding....
for triggering a drop down list to select a specific item you can do like that:
#Html.DropDownListFor(model => model.GroupID, new SelectList((System.Collections.IEnumerable)ViewData["GroupsAvailable"], "Value", "Text", Model.GroupID))
but you must also pass the GroupsAvailable by ViewData or inside your model.
you can pass it like that by ViewData
IEnumerable<SelectListItem> availableGroups = db.Groups
.Where(g => g.IsActive) // for example
.OrderByDescending(c => c.Id)
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.GroupName
});
ViewData["GroupsAvailable"] = availableGroups.ToList();
but over all you question it's not clear what do you want to achieve to answer your second question.

cloning and appending row in a table

How can I perform the following action using jquery?
I have a table with three rows and a header row. something like this:
When a user enters Data in "StudentId" field, "StudentFirstName" and "StudentLastName" are populated from database using jquery-Ajax. What I want to achieve is, Once a studentId is entered in first row textbox, I want to clone the first row and append it as second row and then clear the data from first row.
Hers is my Table structure:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%# Import Namespace="MyModel.Model" %>
<div>
<table id="MyTableHeaders">
<tr>
<th>
StudentId
</th>
<th>
StudentFirstName
</th>
<th>
StudentLastName
</th>
</tr>
</table>
</div>
<div>
<table id="MyTableData">
<tr>
<td>
<input name="StudentId"/>
</td>
<td>
<input name="StudentFirstName"/>
</td>
<td>
<input name="StudentLastName"/>
</td>
</tr>
</table>
</div>
Here is my jquery:
$('input[name="StudentId"]').focusout(function (e) {
e.preventDefault();
var link = '/Student/DisplayStudentDetails';
$.ajax({
type: 'POST',
url: link,
data: { id: $('input[name="StudentId"]').val() },
dataType: 'json',
success: function (result) {
$('input[name="StudentFirstName"]').val(result.FirstName);
$('input[name="StudentLastName"]').val(result.LastName);
$("#MyTableData tr:first").clone().appendTo("#MyTableData");
$("#MyTableData tr:first").find("input").attr("value", "").blur();
},
error: function (result) {
alert("Failed")
}
});
});
I am struggling with clearing data from first row and keeping data in the cloned row. With my code it clears all the rows.
Also, I noticed that cloned rows have the same field names, hence it will update all cloned "StudentFirstName" and "StudentLastName" fields with the studentId entered in first row. How should I approach this?
Any help would be appreciated.
success: function (result) {
var clone = $("#MyTableData tr:first").clone();
clone.find('input[name="StudentId"]').val(result.FirstName);
clone.find('input[name="StudentFirstName"]').val(result.FirstName);
clone.find('input[name="StudentLastName"]').val(result.LastName);
$("#MyTableData ").append(clone);
},
-edit-
although, when i've attempted tasks such as this in the past, i've created template rows.
a row that already exists but has display:none. that way if your table has no values you can always know the template row exists.
-edit-
if you want to add the new row at the begining, you can just use prepend instead of append.
or the second row would be $("#MyTableData tr").first().after(clone)

Categories