Having issue creating a datatable after passing an argument - c#

I am taking a reference from this site. But I have made a slight change in it which is, I am passing an argument which gets branchId. I only wanted to show which are in particlular branch but I am having a issue about how can I return with data as I am having an error.
The parameters dictionary contains a null entry for parameter
'branchId' of non-nullable type 'System.Int32' for method 'Void
GetEmployeeLists(Int32)' in 'xxx (filelocation)'. To make a parameter
optional its type should be either a reference type or a Nullable
type. Parameter name: parameters
MyController
[WebMethod]
public void GetEmployeeLists(int branchId)
{
var id = this._branches.GetById(branchId);
string conn_str = ConfigurationManager.AppSettings["appDB"];
List<EmployeeList> lstDatas = new List<EmployeeList>();
string query = "SELECT " +
#"el.id, " +
#"el.name, " +
#"el.role " +
#"FROM employee_list el;"
using (SqlConnection connection = new SqlConnection(conn_str))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 3000;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
EmployeeList lstData = new EmployeeList();
lstData.Id = Convert.ToInt32(reader["id"]);
lstData.Name = reader["name"].ToString();
lstData.Role = reader["role"].ToString();
}
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
HttpContext.Response.Write(js.Serialize(lstDatas));
connection.Close();
}
}
MyView which contains script
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: '<%=this.Url.Action("GetEmployeeLists", "Admin") %>',
method: 'post',
dataType: 'json',
success: function(data) {
$('#datatable').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
columns: [
{ 'data': 'Id' },
{ 'data': 'Name' },
{ 'data': 'Role' },
]
});
}
});
});
</script>

I have created that this way and I was able solve that issue. However, I have used datatable legacy so you might have to change some of the part.
<script type="text/javascript">
$(document).ready(function() {
var branchId = '<%=ViewData["branchId"]%>';
$.ajax({
url: '.../Admin/GetEmployeeLists', (Needs to change that as per your method location)
method: 'post',
dataType: 'json',
data: {
branchId: branchId
},
success: function(data) {
$('#datatable').dataTable({
"bPaginate": true,
"bSearchable": true,
"sScrollY": "200px",
"aaData": data,
"aoColumns": [
{ 'data': 'Id' },
{ 'data': 'Name' },
{ 'data': 'Role' },
]
});
}
});
});
</script>
Also you need to add the viewdata into your controller
public void GetEmployeeLists(int branchId)
{
...
ViewData["branchId"] = branchId;
}

This has nothing to do with the database. As the error says:
The parameters dictionary contains a null entry for parameter 'branchId' of non-nullable type 'System.Int32' for method 'Void GetEmployeeLists(Int32)' in 'xxx (filelocation)
Your method requires a branchId parameter but your Javascript code didn't pass one:
url: '<%=this.Url.Action("GetEmployeeLists", "Admin") %>'
You should pass the branchId parameter to the action, eg:
url: '<%=this.Url.Action("GetEmployeeLists", "Admin", new { branchId = 123 }) %>'

Related

Jquery/Ajax autocomplete textbox not working in ASP.net

I have a text box that I am trying to have autocomplete with values from a database. The code is, however, not doing anything when I begin typing in the text box. Does anyone have any idea how to fix this? The Scripts are in the head of the page.
<asp:TextBox placeholder="Search by job title" runat="server" CssClass="search" ID="searchTitle"></asp:TextBox>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function () {
$("#searchTitle").autocomplete({
source: function (request,response) {
var param = { posting_jobPosition: $("#searchTitle").val() };
$.ajax({
url: "jobseekerHome.aspx/GetTitles",
data: JSON.stringify(param),
type: "post",
contentType: "application/json; charset=utf-8",
datafilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) { return {value: item }}))
},
});
},
minlength: 1
});
});
</script>
[WebMethod]
public static List<string> GetTitles(string posting_jobPosition)
{
string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(CS);
List<string> Titles = new List<string>();
string query = string.Format("SELECT posting_jobPosition FROM BusinessJobPosting WHERE (posting_jobPosition LIKE '%{0}%' AND isActive = true)", posting_jobPosition);
OleDbCommand oleCom1 = new OleDbCommand(query, Connection);
Connection.Open();
OleDbDataReader reader = oleCom1.ExecuteReader();
while (reader.Read())
{
Titles.Add(reader[0].ToString());
}
Connection.Close();
return Titles;
}
Thanks guys :)
One possible reason that I see is the ID. Change the id as:
$("#<%=searchTitle.ClientID%>").autocomplete({
related: Accessing control client name and not ID in ASP.NET

how to get session value in asmx method asp.net

How can i get session value to the web method . I have tried but it giving me the object reference not set to be instance of object . Any body know the issue .i want to get first method session value in my second method .
how can i do it . i am getting value form my ajax function to my asmx page in getid method . but i want that it to be in my second method as parameter so that i can perform search process
The full code is here
**javascript code**
<script type="text/javascript">
$(document).ready(function () {
$('#btn').on('click', function () {
$.ajax({
url: 'EmployeeWebService.asmx/GetEmployees',
data: { id: '2'}, //this is id i want to get
dataType: "json",
method: 'post',
success: function (data) {
},
error: function (err) {
alert(err);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#btn').on('click', function () {
$('#datatables').DataTable({
columns: [
{ 'data': 'Id' },
{ 'data': 'FirstName' },
{ 'data': 'LastName' },
{ 'data': 'Gender' },
{ 'data': 'JobTitle' },
{
data: "TotalQuestions", render: function
(data, type, row) {
return '<button type="button" data-id=" '
+ row.Gender + ' " class="get_tsk" style="background-
color:steelblue;color:white;border:none;">view</button> '
}
},
],
bServerSide: true,
sAjaxSource: 'EmployeeWebService.asmx/GetEmployees',
sServerMethod:'post'
});
});
});
</script>
**first Method**
First Method
string nameofid;
[WebMethod(EnableSession = true)]
public void GetId(string id)
{
Session["nameofid"] = id;
}
**Second Method**
public void GetEmployees(string id,int iDisplayLength,int
iDisplayStart,int
iSortCol_0,string sSortDir_0,string sSearch)
{
int displayLength = iDisplayLength;
int displayStart = iDisplayStart;
int sortCol = iSortCol_0;
string sortDir = sSortDir_0;
string search = sSearch;
int filteredRows = 0;
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//
List<Employee> listEmployee = new List<Employee>();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Id", SqlDbType.NVarChar, 50).Value =id;
SqlParameter paramDisplayLength = new SqlParameter()
{
ParameterName = "#DisplayLength",
Value = displayLength
};
cmd.Parameters.Add(paramDisplayLength);
SqlParameter paramDisplayStart = new SqlParameter()
{
ParameterName = "#DisplayStart",
Value = displayStart
};
cmd.Parameters.Add(paramDisplayStart);
SqlParameter paramSortCol = new SqlParameter()
{
ParameterName = "#SortCol",
Value = sortCol
};
cmd.Parameters.Add(paramSortCol);
SqlParameter paramSortDir = new SqlParameter()
{
ParameterName = "#SortDir",
Value = sortDir
};
cmd.Parameters.Add(paramSortDir);
SqlParameter paramSearchString = new SqlParameter()
{
ParameterName = "#Search",
Value = string.IsNullOrEmpty(search) ? null : search
};
cmd.Parameters.Add(paramSearchString);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
filteredRows = Convert.ToInt32(rdr["TotalCount"]);
Employee employee = new Employee();
employee.Id = Convert.ToInt32(rdr["Id"]);
employee.FirstName = rdr["FirstName"].ToString();
employee.LastName = rdr["LastName"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.JobTitle = rdr["JobTitle"].ToString();
listEmployee.Add(employee);
}
}
var result = new
{
iTotalRecords = GetEmployeeTotalCount(),
iTotalDisplayRecords = filteredRows,
aaData = listEmployee
};
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}
private int GetEmployeeTotalCount()
{
int totalEmployees = 0;
string cs =
ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select count(*) from
tblEmployees", con);
con.Open();
totalEmployees = (int)cmd.ExecuteScalar();
}
return totalEmployees;
}
}
Add Route Config File below Line :
routes.IgnoreRoute("{x}", new { x = #"..asmx(/.*)?" });
Add WebService File :
[WebMethod(EnableSession = true)]
[ScriptMethod]
public string HelloWorld()
{
if (HttpContext.Current.Session["SessionDetail"] != null)
{
string _SessionData = Convert.ToString(HttpContext.Current.Session["SessionDetail"]);
}
return "Hello World";
}
Assign Session Value :
public ActionResult Index()
{
Session["SessionDetail"] = "Value for Session";
return View();
}
Well, first, you using this:
Session["nameofid"] = id;
and then this:
HttpContext.Current.Session["nameofid"].ToString();
The next issue is how are you calling these methods? If you using say jQuery.ajax?
Remember they are async calls. If you call to set and then in the same code stub call the 2nd routine, it will often fail since such calls are async.
You "could" consider using async = false in the ajax calls, but browers (and jQuery) is now warning that non async calls will not be allowed or supported.
What this means? Be carefull, and if you do a web method call to SET a value, then you need to split out the code that follows to a seperate routine.
we used to do:
function ShowPdf(pID) {
// set/save the id
$.ajax({
type: "POST",
async: false,
url: 'ProjectUpload.aspx/SetChoice',
data: '{strSess:"ProofID", strValue:' + pID + '}',
contentType: "application/json",
datatype: "json"
});
// MORE code here - and MAYBE some code that calls or MIGHT
// use the value based on the ABOVE web method call
// but we CAN'T use async: false anymore!
// so we CAN NOT write code folling here that needs or
// assumes the above call is finished - this code does not
// wait.
So, above code becomes this:
function ShowPdf(pID) {
// set/save the id
$.ajax({
type: "POST",
success: ShowPdf2, <- AFTER code now is moved to this rouine
url: 'ProjectUpload.aspx/SetChoice',
data: '{strSess:"ProofID", strValue:' + pID + '}',
contentType: "application/json",
datatype: "json"
});
}
function ShowPdf2() {
// split out due to we have to wait async
// for web call to complete. This code ONLY runs WHEN
// the above web call is 100% done. Even if web server is slow today!
// MUST set session() ProofID before calling this routine
// show a dialog in this page pdfdiv
var mydiv = $('#pdfdiv');
mydiv.dialog({
autoOpen: false, modal: true, title: 'Proofing: ', width: '100%',
position: {
my: "center top",
at: "center top+80"
},close: myempty,
dialogClass: 'dialog-no-close'
});
mydiv.load('../PDF1.aspx');
// Open the dialog
mydiv.dialog('open');
// }
}
So, the above code was failing since the following the web call would start running before the session() set ajax call was done.
Setting async: false DID work well, but in the browser debug, we saw warnings that async:false will soon not be supported in jQuery (or web browsers). So, you wire up a routine to run when the async call is done and move out the code that follows to that routine so, the code that follows was moved out and called by the jQuery (success: event).
So, it not clear how/when/where your code calls the first web method, but if any code call FOLLOWS to check/see/grab/get/look at the session() value to be return from the 2nd web method? You have to deal with the async issue.
and depending on your imports (using for c# folks), then if you need to include the namespace before using session() in a web method.
I find I have to use this:
HttpContext.Current.Session(strSess) = strValue
So, I would use the same name space reference in both your web methods - is it NOT AT ALL clear why you left out the name space in one code stub, but put it in the other.
As noted, it also not clear how your js is testing/getting the session() value, but as noted, the first web call to set the session() will NOT wait, and you find sometimes that when you call the 2nd routine to get the session(), the first routine may well not yet have finished (since the calls are async).
Check my below screenshot and follow the steps:

Not Receiving the query result to ajax function from asmx page asp.net

I'm working with the Ajax and jQuery in my app. When I return a query result it's not showing me that result. The Code is given below:
asmx page Code
[WebMethod, ScriptMethod]
public void Getusertimelist(string id)
{
List<UserhoursList> employeelist = new List<UserhoursList>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString))
{
con.Open();
SqlCommand command12 = new SqlCommand(" SELECT CONVERT(TIME, DATEADD(s, SUM(( DATEPART(hh, Total_time) * 3600 ) + ( DATEPART(mi, Total_time) * 60 ) + DATEPART(ss, Total_time)), 0)) From Todaywork Where Id='"+id+"'", con);
string getvalue = command12.ExecuteScalar().ToString();
UserhoursList employee = new UserhoursList();
employee.Total_Time = getvalue;
employeelist.Add(employee);
con.Close();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(employeelist));
//return id;
}
Ajax Code
<script type="text/javascript">
$(document).on("click", ".get_time", function () {
var timeid = $(this).data('id');
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: { id: timeid },
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
});
$(document).ready(function () {
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
});
});
</script>
It's not showing me the answer because when I remove that (string id) parameter then it works perfectly. When I use it's not showing me the answer. I want to complete my project but this error not pushing me. Any help plz.
Your first request looks good. But in your second request, I don't see that you're using the jQuery DataTable data option.
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
// Where is data: { id: timeid }?
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
I think it will work if you change data to send a string
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: '{ "id": ' + timeid + '}',
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
an alternative is do something like
var dat = {}
dat.id = timeid
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: JSON.stringify(dat),
success: function (data) {
//alert(data);
},
error: function (err) {
}
});

How to display viewbag on view on HttpPost

I want to be able to display the ViewBag on view on button click event, this is my code:
[HttpPost]
public ActionResult SpecificWorkflowReport(Report2ListViewModel wf)
{
var getSpRecord = db.Mworkflow().ToList();
var getRecord = (from u in getSpRecord
select new Report2ListViewModel
{
WorkFlowType = u.WorkFlowType,
WorkflowInstanceId = u.WorkflowInst,
WorkFlowDescription = u.WorkFlowDesc,
}).ToList();
ViewBag.WorkflowType = wf.WorkFlowType;
ViewBag.WorkflowInstanceId = wf.WorkflowInst;
ViewBag.WorkFlowDescription = wf.WorkFlowDesc
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord);
return Json(data);
}
i have tried this:
Worflow Type: #ViewBag.WorkflowType
Workflow Instance Id: #ViewBag.WorkflowInstanceId
Workflow Description: #ViewBag.WorkFlowDescription
My Javascript and json Call:
<script type="text/javascript">
$(function () {
var table = $("#reportTable").DataTable();
var url = $("#frmSpecificWorkflowReport").attr('action');
var str = $("#frmSpecificWorkflowReport").serialize();
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
if (_data.f !== undefined) {
swal({
title: "Empty Result Set",
text: "No record found",
type: "info"
});
table.clear();
return false;
}
var arr = $.map(JSON.parse(_data), function (el) { return el
});
if (arr.length === 0) {
swal({
title: "Empty Result Set",
text: "No record found",
type: "info"
});
}
table.clear();
table.destroy();
$('#reportTable').dataTable({
data: arr,
columns: [
{ "data": "WorkFlowType" },
{ "data": "WorkflowInstanceId" },
{ "data": "WorkFlowDescription" },
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'LEGAL'
}
]
});
table = $("#reportTable").DataTable();
but the ViewBag values are always null on the view, any assistance will be appreciated. I just added Javascript and json call to the post, i want to be able to retrieve my stored data and display it anywhere on the view
#UwakPeter your code snippets is ok, but you are returning Json, may be you are calling this method via javascript, so the view is not updating, you need to reload the view, by the submit button.
If you are using javascript, you can pass your data list and model data as anonymous object, so that you don't need to use ViewBag. in client side by ajax success function you can grab them (WorkflowType, WorkflowInstanceId, WorkFlowDescription, Result)
[HttpPost]
public ActionResult SpecificWorkflowReport(Report2ListViewModel wf)
{
var getSpRecord = db.Mworkflow().ToList();
var getRecord = (from u in getSpRecord
select new Report2ListViewModel
{
WorkFlowType = u.WorkFlowType,
WorkflowInstanceId = u.WorkflowInst,
WorkFlowDescription = u.WorkFlowDesc,
}).ToList();
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord);
return Json(new{
WorkflowType = wf.WorkFlowType,
WorkflowInstanceId = wf.WorkflowInst,
WorkFlowDescription = wf.WorkFlowDesc,
Result= data
}, JsonRequestBehaviour.AllowGet);
}
JS
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
var workflowType=_data.WorkflowType; //set it to HTML control
var workflowInstanceId =_data.WorkflowInstanceId;
var workFlowDescription = _data.WorkFlowDescription;
$('#reportTable').dataTable({
data: _data.Result
});
}
)};
Try this,
#{
Layout = null;
ProjectMVC.Models.Record record= (ProjectMVC.Models.Record)ViewBag.Recorddetails;
}
...
Worflow Type: #record.WorkflowType

asp.net webservice jquery textbox autocomplete

I'm trying to implement jquery - textbox autocomplete. for this setup a web service.
[WebMethod]
public List<Condition> GetCondition(string term)
{
List<Condition> listCondition = new List<Condition>();
string cs = ConfigurationManager.ConnectionStrings["db5"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSelCondition", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listCondition.Add(new Condition { ConditionID = rdr["ConditionID"].ToString(), ConditionName = rdr["ConditionName"].ToString() });
}
return listCondition;
}
}
public class Condition
{
public string ConditionName { get; set; }
public string ConditionID { get; set; }
}
WebService works perfectly fine. To populate the textbox with jquery autocomplete this javascript I've written.
<script type="text/javascript">
$(document).ready(function () {
$('#txtCondition').autocomplete({
source: function (request, response) {
$.ajax({
url: 'ibs_ws.asmx/GetCondition',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: request.term }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
}
});
})</script>
When I access the webservice it takes the #term as parameter and returns the result with ConditionID and ConditionName in xml formate. But on the webform when I give type anything in the textbox it alerts with [object object].
What could be the problem.
--
Thanks & Regards
May be it will help you. try this
I think you need to use $.map(data.d, function (value, key) {}). here is the example need to update your success code like below then you can get value inside object.
success: function (data) {
response($.map(data.d, function (value, key) {
return {
ConID: value.ConditionID,
ConNAme: value.ConditionName,
}
}))
},
AS you said your service returns conditionID and Name so i used these variable you can match what it returns exactly.

Categories