Web grid search function using JS and ASP.NET MVC - javascript

I am using ASP.NET MVC. I try to implement search box.
I have a input box and a button:
<div>
<input type="text" name="Search" id="Search" />
<input type="submit" value="Search" id="SearchButton" />
</div>
Then I use JS to receive user input and trigger a function:
$(document).ready(function () {
$('#SearchButton').click(function Search() {
$.ajax({
url: '#Url.Action("Search", "PCA")',
data: { AutoCribItemID: $('#Search').val() },
type: "POST",
dataType: "json",
success: function (result) {
var data = new Array();
for (var i = 0; i < result.Data.length; i++) {
data.push(result.Data[i]);
}
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
});
Then in back end, there is a respond method:
[HttpPost, ActionName("Search")]
public JsonResult Search(string AutoCribItemID) {
List<PCAModel> allRecords = new List<PCAModel>();
allRecords = db.elements.Where(model => model.AutoCribItemID.Contains(AutoCribItemID)).ToList();
return Json(new { Data = allRecords }, JsonRequestBehavior.AllowGet);
}
You can see this C# method returns a list to frontend. Then what I want to do is to show all data after searching to user.
Here is a method to show data after searching:
function loadData(result) {
var table = $('<table id="indexTable"></table>');
var thead = $('<thead></thead>');
var trow = $('<tr class="header"></tr>');
trow.append('<th>EffectiveDate</th>');
trow.append('<th>ChangeAgree</th>');
trow.append('<th>Client</th>');
trow.append('<th>Installation</th>');
trow.append('<th>AutoCribItemID</th>');
trow.append('<th>RGBSupplier</th>');
trow.append('<th>Price</th>');
trow.append('<th>SubmitDate</th>');
trow.append('<th>WINUserName</th>');
trow.append('<th>Export</th>');
thead.append(trow);
table.append(thead);
var tbody = $('<tbody></tbody>');
for (var i = 0; i < result.length; i++) {
tbody.append(result[i]);
}
table.append(tbody);
$('#indexTableBody').html(table);
location.reload();
}
Note: 'result' parameter above is from C# function from backend.
The question is, web page shows all record in the table instead of showing searched data. I only need to show data after searching in web grid.

Without knowing the structure of your AutoCribItemID's, my guess is that because you're using .Contains in your where clause it's returning anything that matches that search term. So, for example, if you had integer IDs and someone searched for "1", it would return any ID that contains the number 1 including 1, 10, 11, 12, 13, etc. You probably want to use an equality comparison instead, i.e. model.AutoCribItemID == AutoCribItemID

Related

HTML value passed to WebService is showing NULL

I have a AJAX Web Serice that runs an SQL statment, which works.
I am trying to take an HTML value from my web page and use it as an additional variable in my query.
Here is how I am capturing that variable on my web page.
<div style="margin-left:0px">
<label>Enter Number here: </label><br>
<input type= text id="demo">
</div>
...and this is my Web Service call.
//Generate code
function Generate() {
var myGrid = $('#jqquotes'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow');
docid = myGrid.jqGrid('getCell', selectedRowId, 'docid');
document.getElementById("demo").innerHTML = document.getElementById("demo").value;
alert(document.getElementById("demo").value);
var quotenum = document.getElementById("demo".value);
if (confirm('Are you sure you want to generate a quote?')) {
$.ajax({
url: '/WebService1.asmx/Generate',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "GET",
data: { docid: docid, quotenum: JSON.stringify(quotenum) },
success: function () {
//Get selected
var grid = $("#jqquotes");
var rowKey = grid.jqGrid('getGridParam', "selrow");
//Refresh grid
$('#jqquotes').trigger('reloadGrid');
//Set Selected
setTimeout(function () {
jQuery('#jqquotes').jqGrid('setSelection', rowKey);
}, 200);
}
});
} else {
return false
}
}
The alert box correct displays the HTML value from the box id "Demo"
But the WebService fails, saying the value is NULL, JSON reponse is:
Message "The parameterized query '(#docid nvarchar(5),#quotenum nvarchar(4000))UPDATE [dbo].[quote' expects the parameter '#quotenum', which was not supplied."
...and the GET URL shows the value as NULL
https://localhost:44338/WebService1.asmx/Generate?docid=10146&quotenum=null
Any help greatly appreciated.
I think the problem is here:
var quotenum = document.getElementById("demo".value);
This should be
var quotenum = document.getElementById("demo").value;
as in the line above it.

How to update data in SQL for an html table row using Input Button, in JS or C#?

I have a datatable in C# and I am converting it to html table like below.
public static string ConvertDataTableToHTML(DataTable dt)
{
StringBuilder html = new StringBuilder();
html.Append("<table id='example' class='table table-striped table-bordered' cellspacing ='0' width ='100%' font size='8' aria-hidden='true'>");
//add header row
html.Append("<thead>");
html.Append("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
html.Append("<td>" + dt.Columns[i].ColumnName + "</td>");
html.Append("<td>" + "Action" + "</td>");
html.Append("</tr>");
html.Append("</thead>");
//add rows
for (int i = 0; i < dt.Rows.Count; i++)
{
html.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
html.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
html.Append("<td><input type=\"button\" value=\"Delete\" onclick=\"deleteRow(this)\"/></td>");
html.Append("</tr>");
}
html.Append("</table>");
return html.ToString();
}
This is showing a table in my aspx page like below:
Name City Quantity Action
A X 5 Delete
B Y 10 Delete
C Z 15 Delete
When I click "Delete" button for a row, the function below works and the row is gone from the result table.
<script>
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
</script>
What I want is that, in addition to the current process, I need to run a SQL query to update IsRemoved flag for this data in my SQL Server 2014 table.
The query I need to run: Update MyTable set IsRemoved=1 where Name='A' and City='X'
I could not manage to run it in JavaScript function, and could not find a way to execute another function in C# after the JS function. OnClientClick is not working since it is not an asp:Button, and when I try to use asp:Button instead of input element, it does not show it on the screen.
How can I change data in DB here for such an example? Please note that I am trying not to use a GridView. Any help would be appreciated.
EDIT: By using Ajax, how can I send paramaters from my ajax call to c#:
I am trying:
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
data: JSON.stringify({ name: **<nameshouldcomehere>**, city:**<cityshouldcomehere>** }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
I can't find how to set name and city dynamically based on the row clicked the delete button, any tips?
In your .cs page create a WebMethod which will mark the Database entry as IsRemoved=1 as:
[System.Web.Services.WebMethod]
public static string DeleteRowFromDB(string name,string city)
{
var status = "0";
//Your code to mark `IsRemoved=1` for the selected entry goes here and set the `status` variable as status="1" if the DB command successed.
return status;
}
And then create a function with an ajax call to invoke the created WebMethod and remove the row from HTML if the status is true as:
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
var cells = row.getElementsByTagName("td");
var reqData = JSON.stringify({ name: cells[0].innerText, city:city=cells[1].innerText });
//now make a call to the `WebMethod` via `ajax`.
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
contenttype: 'application/json; charset=utf-8',
data: reqData,
datatype: 'json',
success: function (response) {
if(response === "1") {
row.parentNode.removeChild(row);
}
else
{
//do other stuff
}
},
error: function (error) {
//handle the error
}
});
}
Note: if the response variable in the ajax success function doesn't have the desired value try to look for its response.d property value.

Cannot read property 'row' of undefined

//anything inside 'pagebeforecreate' will execute just before this page is rendered to the user's screen
$(document).on("pagebeforecreate", function () {
printheader(); //print the header first before the user sees his page
});
$(document).ready(function () {
searchfriend();
function searchfriend() {
var url = serverURL() + "/getcategories.php";
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getCategoryResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _getCategoryResult(arr) {
var t; //declare variable t
//loop for the number of results found by getcategories.php
for (var i = 0; i < arr.length; i++) {
//add a new row
t.row.add([ //error
"<a href='#' class='ui-btn' id='btn" + arr[i].categoryID + "'>Category</a>" //add a new [Category] button
]).draw(false);
//We drew a [View] button. now bind it to some actions
$("#btn" + arr[i].categoryID).bind("click", { id: arr[i].categoryID }, function (event) {
var data = event.data;
showcategory(data.id); //when the user clicks on the [View] button, execute showcategory()
});
}
$("#categoryresult").show(); //show the results in the table searchresult
}
function showcategory(categoryID) {
//alert(categoryID);
window.location = "showuser.html?userid=" + userid;
}
});
There is an error on line 33 which stated:
"Uncaught TypeError: Cannot read property 'row' of undefined"
However, it seems that I have no idea where the error is coming from.
Is there anyway I can solve this problem?
You look like you are using a third-party jQuery plugin, DataTables.
Follow the usage of DataTables.
var t; //declare variable t
should be
var t = $("#categoryresult").DataTable();
The variable t is not an object with a property called row.
Try with var t = { row: [] }
Edit: I apologize. I got confused add with push method.
So, you need an object with a method called add and assign that object to t

Reload div fires constantly without event MVC

I am working on a project in Visual studio using MVC. I am trying to reload a div after a btn is clicked and data has been posted to the controller dynamically. I use an Ajax post and return a JSONresult. The code for posting looks like this:
<div id = "DelUser">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Dform" }))
{
<label> Select User(s) to Delete: </label>
#Html.ListBox("Users", ViewBag.Users as MultiSelectList,
new { #class = "chzn-select", #style = "width:250px; height:350 px" })
}
<button class="btn btn-primary dropdown-toggle" id="Button1" type="button" onclick="DeleteUsers()"> Delete Selected </button>
</div>
<script>
function DeleteUsers() {
var myList = []
$("#Users > option:selected").each(function () {
myList.push($(this).val());
});
jQuery.ajax({
type: 'post',
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: 'DeleteU',
data: JSON.stringify(myList),
success: function (data) {
$('#msgbx2').html(data.msg);
//here I am trying to refresh the div after the post but it fires every second
$('#DelUser').html('/Home/DeleteUser');
},
failure: function (errMsg) {
$('#msgbx2').html(data.msg);
}
});
return false;
}
The name of the controller is DeleteUser and the JSONresult controller is DeleteU.
I am trying to do this so that the dropdownlist updates after I delete the selected users. If there is another way to dynamically update this div, any information on that would be good to know too. Thank you in advance.
Here are the Controllers as well:
[HttpGet]
public ActionResult DeleteUser()
{
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] user in users)
{
u.Add((string)user[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
return View();
}
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{
bool good = false;
if (Users != null)
{
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
good = data.insert_update_delete_DB(ins);
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] usera in users)
{
u.Add((string)usera[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
if (good == true)
{
ViewBag.error = "You have successfully deleted user";
}
else
{
ViewBag.error = "There was an issue removing user";
}
}
return Json(new { msg = "You have Successfully deleted Users " });
}
return Json(new { msg = "the passwords entered do not match" });
}
This is just a section of my main page that has other action functions/controllers in it which is why i did not originally post the controllers
You can simply update the existing listbox by removing the currently selected items. Start by removing onclick="DeleteUsers() from the button and use Unobtrusive JavaScript. Since you do not appear to have a POST method for DeleteUser() or a submit button, you may as well also replace #using (Html.BeginForm(...)) with just <form> elements. The script will then be
$('#Button1').click(function () {
var selected = $('#Users option:selected'); // store the selected users
if (selected.length == 0) {
return; // no point making a post
}
var users = [];
$.each(selected, function (index, item) {
users.push($(this).val());
})
$.ajax({
type: 'post',
dataType: 'json',
url: '#Url.Action("DeleteU", "yourControllerName")', // always use Url.Action to generate your url's
data: { users: users },
traditional: true,
success: function () {
// remove the currently selected options
selected.remove();
}
});
})
However a lot of the code in your controller does not make sense. Your adding values to ViewBag and even creating a SelectList but your not returning a view (your returning json), so all that is lost. And even if you were returning a view, your loop keeps overwriting the value of ViewBag.error so that only the last value would be set. Ideally, you should be calling a service to delete the users by passing the user name (or a collection of user names so that they are all deleted in a transaction). But based on you current code, you controller method can be
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{
if (Users == null)
{
// throw an error that can be caught in the ajax error handler
}
List<string> deletedUsers = new List<string>();
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
if (data.insert_update_delete_DB(ins))
{
deletedUsers.Add(user);
}
}
return Json(deletedUsers);
}
and then the ajax success callback
success: function (data) {
$.each(data, function(index, item) {
// remove each item that was successfully deleted in the controller
$('#Users option:contains("' + item + '")').remove();
}
}
i think you need to add a $(document).ready(function(){}); around your script

ajax postback method for refreshing dropdown list

Scoop...
I have a drop down list that might not display a particular option you're looking for. I added a button with pop up modal to type in a field you want to add to the drop down list. It functions perfectly, but I need to add an ajax postback method to refresh the list after the user hits enter. I don't want to refresh the whole page, just the list. any help?
Controller:
public ActionResult AddLeadSource()
{
return View();
}
[HttpPost]
public ActionResult AddLeadSource(string name)
{
LeadSource ls = new LeadSource();
ls.Name = name;
db.LeadSources.Add(ls);
db.SaveChanges();
return Json(new { success = true });
}
JS
<script>
$("#AddNew").change(function () {
var name = $("#Name").val();
// var order = $("#DisplayOrder").val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
url: '/Admin/LeadSource/AddLeadSource',
data: { name: name },
success: function (response) {
//alert("Success " + response.success);
$('#FollowUpNotes').kendoWindow('destroy');
// Refresh the DropDown <-- Heres where I need some help!
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});
In your success function of your Ajax call add this:
$("IdOfDropDownList").data("kendoDropDownList").dataSource.read();
In this way your dropdownlist will call the read function and reload all data. I assumed that your dropdownlist is binding throught read call.
I highly recommend looking at jQuery UI's autocomplete widget. That said,
$('#YourDropDownID option').remove(); //this will remove all option elements inside the <select id="YourDropDownID">
Then you just need to build new ones based on the response data,
for (var o in data) {
if (data[o].Value != undefined) {
$('#YourDropDownID').append('<option value="' + data[o].Value + '">' + ("" + data[o].Display) + '</option>');
}
}
I do this inside the .done() callback of my AJAX:
.done(function (data) {
//above code
}
Depending on the nature of the data you are sending back you may need to loop through it differently. Mine is an array of objects with a Value and Display properties (in my case, account numbers and account names).
//server side controller
var query = #"
Select
SubString([mn_no], 0, 6) As Value,
RTRIM([acct_desc]) As Display
From [some_table]";
return con.Query(query, new { AccountNumber = accounts.Select(x =>
{
return new { Value = x.Value, Display = x.Display };
});

Categories

Resources