Delete all checked element in list - c#

I display a list of element from a list, and I have to display a checkbox in front of each element, and then delete all checked element, I wrote a jquery code for do this but it removes just the first element checked, how I should do to remove all checked items
<button type="submit" class="btn fsc-btn-3" id="AllDelete">
<i class=" fa fa-check"></i>
<span>#Labels.Global_DeleteSelection</span>
</button>
#foreach (var item in Model.FilesList)
{
<tr>
<td><input type="checkbox" name="checkFile" id="checkFile" value="#item.FileId" /></td>
<td>#item.ArrivalTime</td>
<td>#Model.TraitementDate(item.FileId)</td>
<td>#item.Name</td>
<td>#item.FileType</td>
<td>
<label class="proj-label-1 proj-label-size-1 proj-status-5" title="#item.State">
<i class="fa fa-check-circle"></i>
<span>#item.State</span>
</label>
</td>
<td >#item.NumAlertRecords</td>
<td>#item.NumRejectedRecords</td>
<td >#item.NumAcceptedRecords</td>
}
jQuery code:
(function(jQuery) {
jQuery(function() {
jQuery('#AllDelete').click("click", function() {
jQuery('input[type="checkbox"]').each(function() {
if (jQuery(this).is(':checked')) {
alert(jQuery("#checkFile").val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery("#checkFile").val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);
Controller :
[HttpPost]
public ActionResult DeleteMultiCredit(int FileId)
{
DeleteCreditModel model = new DeleteCreditModel();
model.Delete(FileId);
return RedirectToAction("Index");
}

Try this : first of all you cannot use same id for all checkbox, so either generate unique ids for each one or remove id attribute
#foreach (var item in Model.FilesList)
{
<tr>
<td><input type="checkbox" name="checkFile" value="#item.FileId" /></td>
<td>#item.ArrivalTime</td>
<td>#Model.TraitementDate(item.FileId)</td>
<td>#item.Name</td>
<td>#item.FileType</td>
<td>
<label class="proj-label-1 proj-label-size-1 proj-status-5" title="#item.State">
<i class="fa fa-check-circle"></i>
<span>#item.State</span>
</label></td>
<td >#item.NumAlertRecords</td>
<td>#item.NumRejectedRecords</td>
<td >#item.NumAcceptedRecords</td>
}
now use $(this).val() to get value of each checkbox instead of using id of checkbox to read value
jQuery(function () {
jQuery('#AllDelete').click("click", function () {
//you can use :checked directly in selector, so if condition not required
jQuery('input[type="checkbox"]:checked').each(function() {
alert(jQuery(this).val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },//read your value here
success: function (data) {
}
});
});
});
})(jQuery);

Use jQuery(this) instead of jQuery("#checkFile")
Just like this :
(function(jQuery) {
jQuery(function() {
jQuery('#AllDelete').click("click", function() {
jQuery('input[type="checkbox"]').each(function() {
if (jQuery(this).is(':checked')) {
alert(jQuery(this).val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);

try below code
jQuery(function () {
jQuery('#AllDelete').click(function () {
jQuery('input[type="checkbox"]').each(function() {
if(this.checked){
alert(jQuery("#checkFile").val());
jQuery.ajax({
url: '#Url.Action("DeleteMultiCredit", "DeleteCredit")',
type: "POST",
dataType: "json",
data: { FileId: jQuery(this).val() },
success: function (data) { }
})
}
});
});
});
})(jQuery);

Related

Calling a linkbutton click with jquery

I've got a textbox, I want a function to be called onkeyup, for that reason I've got a hidden button that is trying to redirect to another c# function. The problem is jquery goes inside the function, but then doesn't go to the server side event.
Here's my HTML for both elements:
<div class="row" style="margin-top: 5px;">
<div class="col-sm-12">
<div class="input-group input-group-sm">
<span class="input-group-addon">Име:</span>
<asp:TextBox ID="tbCliName" ClientIDMode="Static" runat="server" onkeyup="runQuery(this)" CssClass="form-control"></asp:TextBox>
<asp:LinkButton ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:LinkButton>
<span class="input-group-addon">Егн/Булстат:</span>
<asp:TextBox ID="tbEgnBStat" ClientIDMode="Static" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</div>
</div>
Here's my jquery funtion:
function runQuery(e) {
$('#hiddenButton').click();
}
And the C# for the button click:
protected void hiddenButton_Click(object sender, EventArgs e)
{
AutoComplete_Press(tbCliName.Text);
}
EDIT with Ajax:
function runQuery(e) {
var search = $(e).val();
function runQuery(e) {
var search = $(e).val();
var params = {
url: 'addEditProduct.ascx/AutoComplete_Press',
method: 'post',
contentType: 'aapplication/json',
data: '{searchClause:' + search + '}',
dataType: 'json',
success: function (data) {
alert(1);
},
error: function (data) {
alert(2);
}
};
$.ajax(params);
}
[WebMethod]
public static void AutoComplete_Press(string searchClause)
{
int searchType = 0; //ЕГН
int csKind = 0;
Regex regex = new Regex("^[0-9]+$");
if (!regex.IsMatch(searchClause))
searchType = 1;
//if (rbLP.Checked)
// csKind = 1;
string clients = laboratory.getClients2(searchType, searchClause, 1);
}
try using webmethod. In server side
[WebMethod]
public static void BindData()
{
AutoComplete_Press(tbCliName.Text);
}
And in client side
$("#hiddenButton").click(function() {
$.ajax({
type: "POST",
url: "index.aspx/BindData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({/*pass values here*/}),
dataType: "json",
});
});
Refer below link
https://www.aspsnippets.com/Articles/Calling-server-side-methods-using-JavaScript-and-JQuery-in-ASP.Net.aspx
The reason why it is not working is that you are using asp:LinkButton which is rendered as a element with href attribute set to javascript:__doPostBack().
If you replace asp:LinkButton to asp:Button calling $('#hiddenButton').click(); will start to work.
Just change this line of code
<asp:LinkButton ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:LinkButton>
to this
<asp:Button ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:Button>
You can invoke function like this but not event
Create a Web Method and try Jquery Ajax
var params = {
url: 'Index.aspx/YourWebmethod',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
data: JSON.stringify(data to be send ),
success: function (result) {
alert('Success');
},
error: function (result) { alert('Warning! It failed.'); }
};
$.ajax(params);

Pass parameter from View to controller MVC 4

I want to pass selected value of dropdownlist from view to controller in html.BeginForm in MVC 4.
I can pass value of query string, but I have no idea about how to pass selected value of dropdownlist.
All suggestions are most welcome.
Here is my code attached
<form>
<fieldset class="form-group" id="ddl2">
<label for="exampleSelect1">Section Type:</label>
#(Html.Kendo().DropDownList()
.Name("ddlsection")
.DataTextField("Name")
.DataValueField("Id")
.OptionLabel("--Select--")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetSectionType", "LookUp");
});
})
.Events(e => e.Change("onChange_ddlsection"))
.HtmlAttributes(new { #class = "form-control" })
)
</fieldset>
</form>
<div class="WordClass">
#using (Html.BeginForm("GetConditionListingInWord", "Inspection", new { sectionId = 'What should be here?' }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="Submit1" type="submit" value="" class="WordClassA tooltipSource" title='Print List in MS-Word format' data-placement='bottom' data-toggle='tooltip' />
}
</div>
I want 'ddlsection' dropdown's selected value in 'What should be here?' section.
You can pass Kendo Dropdownlist's selected value to the Controller using Ajax call and then redirect to another Action if you want as shown below:
<script type="text/javascript">
$(function () {
//Returns Dropdownlist's selected values to the Controller
$("#btnSubmit").click(function (e) {
e.preventDefault();
var data = {
ProjectID: $('#ProjectID').val(), //parameter I
IssueID: $('#IssueID').val() //parameter II
}
$.ajax({
type: "POST",
url: "/Controller/Action",
cache: false,
data: JSON.stringify(data),
dataType: this.dataType,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Variable data contains the data you get from the action method
window.location = "/Controller/OtherAction/" + data
},
error: function (data) {
$("#error_message").html(data);
}
});
});
});
</script>
For that you have to make AJAX call to your controler method
var userModel = {
RoleId: $("#drpRoleId").data("kendoDropDownList").value(),
}
$.ajax({
url: '#Url.Action("AddEditUser","User")',
type: 'POST',
data: JSON.stringify(userModel),
async: true,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
}
});

Table with combobox on one of fild data-binding

I need create table with field with combobox on page. But I can't bind valid items to combobox, all combobox have default values - 'Please Select...'. Can you help me?
My html code fragment:
<td><label data-bind="text: name"></label></td>
<td><label data-bind="text: description"></label></td>`enter code here`
<td>
<select class="controls contol-width span2" id="cmbSelectedInfo" required="required" data-bind="
options: vm.infoes,
value: vm.selectedInfoID,
optionsText:'code',
optionsValue: 'infoID',
optionsCaption: 'Please Select...'"></select>
</td>
My viewmodel in typescript:
class MyViewModel {
infoes: KnockoutObservableArray<any>;
selectedInfoID: KnockoutObservable<number>;
constructor() {
this.infoes = ko.observableArray();
this.selectedInfoID = ko.observable<number>();
}
getInfoes(url: string, onError: (message: string) => {}) {
(<any>this).getJson(url, (data: any) => {
<any>this.infoes((<any>ko).mapping.fromJS(data).infoes());
} ,(message: string) => {
onError(message);
});
}
getJson(url: string, onSuccessed: (data: any) => {}, onError: (message: string) => {}) {
var self = this;
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
success: (data) => {
if (data.succeeded) {
onSuccessed(data);
} else {
onError((<any>data).error);
}
},
error: (data) => {
onError((<any>data).error);
}
});
}

Pass ID in Html.ActionLink via ajax to get partial view

I have an MVC View page, strongly-typed to an enumerated product list. Each list item has an Html.ActionLink with a unique id. In my jquery file, I have an $.ajax function which should process the link with the corresponding id . The intent is to load a partial view on the same page, with that item's information, to allow editing for whatever item has been clicked. I don't want the actionr to result in a separate page, or generate a post to the server.
// here is the MVC stuff
#model IEnumerable<SimpleAjax.Models.Product>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.ActionLink("Edit", "ShowEdit", "Home", new { id=item.Id } ,new { id = "btnShowEdit" + item.Id, #class= ".button_action"})
|
</td>
</tr>
}
<div id="showEditProd">
</div>
//inside controller
public ActionResult ShowEdit(int id)
{
Product prod = db.Product.Find(id);
ProductViewModel viewModel = new ProductViewModel
{
EditProduct = prod
};
return PartialView(viewModel);
}
//inside a separate partial view page
#model SimpleAjax.Models.ProductViewModel
#using (Html.BeginForm("Index_AddItem", "Home", FormMethod.Post, new { id = "fid" }))
{
<div>
#Html.LabelFor(model => model.EditProduct.Name)
#Html.EditorFor(model => model.EditProduct.Name)
</div>
<div>
#Html.LabelFor(model => model.EditProduct.Price)
#Html.EditorFor(model => model.EditProduct.Price)
</div>
<div>
<input type="submit" value="Submit" />
</div>
}
now below works as expected, when I have hardcoded IDs:
$('#btnShowEdit1,#btnShowEdit2,#btnShowEdit3').click(function () {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
The above jquery works as desired. The partial view gets loaded on the same page as enumerated list. But obviously I don't want to hardcode variables. I may have x number of #btnShowEdit. I want to utilize a class, correct? So I have ".button_action" class that will enumerate the Id. But when I do that, as below, the link navigates to a separate page.
these go to a separate page, not what I want
$('.button_action').click(function (index) {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
//also tried this...
$('.button_action').each(function (index) {
$('#btnShowEdit' + index).click(function () {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
I know there's gotta be a simple solution.Thanks for your help in advance.
Any specific reason for not using the Ajax HTML-helper?
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.actionlink(v=vs.108).aspx
You can use it as an actionlink, but it is done async and the result can be placed in your showEditProd.
#Ajax.ActionLink("Action",
"Controller",
_YOURID_,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "showEditProd",
OnComplete = "your_js_function();" })
In case anyone else needs the solution to the above... It was too simple to believe.The jquery ajax code does not need an id htmlattribute from the Html.ActionLink. In fact, this extra attribute is what was causing the trouble. The jquery ajax recognizes the id from the "this.href' as that is the route controller along with the id parameter. Therefore I removed the id from htmlattributes in the actionlink. Now it's working as expected.
#Html.ActionLink("Edit", "ShowEdit", "Home", new { id=item.Id } ,new { #class= ".button_action"})
in js file
$('.button_action').click(function (index) {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
Check this:
$('.button_action').click(function (e) {
e.preventDefault() // this prevent default behavior for hyperlink on 'click' event

Jquery Post not reaching MVC Controller

Apologies if this i trivial, i have read many other comments and still cannot see what is wrong. I have done a few tutorials and they seem to work ok, so I am really missing something simple.
I have a basic 'remove' link that i want to do a JQuery Post back to the controller to remove an item from the database and then update the view.
My View / Javascript:
<script type="text/javascript">
$(function () {
$(".RemoveLink").click(function () {
var id = $(this).attr("data-id");
if (id != '') {
$.post("#Url.Content("~/Agent/Remove")", { "id": id }, function (data) { alert('Here i am'); });
}
});
});
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<a href="#" class="RemoveLink" data-id="#item.ID" >Remove</a>
</td>
</tr>
}
My Controller:
[HttpPost]
public ActionResult Remove(int id)
{
return Json(new { Data = "true" });
}
Any assistance will be great.
Use #Url.Action("Remove", "Agent") instead.
#Url.Content("...") is used to locate any static content of the site.
Cheers
Below code works well.
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<input type="button" class="RemoveLink" id="#item.ID" Value="Remove" />
</td>
</tr>
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('.RemoveLink').live("click", function () {
Remove($(this));
});
});
function Remove(_this) {
var Id= $(_this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("Remove", "Agent")',
data: "{id: '" + Id + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
//do something here......
},
error: function () {
}
});
}
</script>

Categories