I am new to Json datatype. how to retrive it.. please look at the code below.
This is my Javascript code:
function fnDeleteSelected() {
var count_checked = $("[name = 'myChkBox[]']:checked").length;
var arrayOfID = [];
$(':[name = "myChkBox[]"]:checked').each(function () {
arrayOfID.push($(this).val());
});
var test = JSON.stringify(arrayOfID);
alert(test);
if (count_checked == 0) {
alert("Please Select a Student to delete");
return false;
}
else {
var confirmDel = confirm("Are you sure you want to delete this?");
if (confirmDel == true) {
jQuery.ajax({
url: baseUrl + "DeleteSelected/",
type: 'Post',
dataType: 'Json',
data: { Parameters: test },
success: function (msg) {
jQuery("input:checkbox:checked").parents("tr").remove();
}
});enter code here
}
}
}
here data send to controller is parameters where parameters = ["143","144","145"]
and my controller is: where Parameters is passed as "[\"143\",\"144\",\"145\"]"my question is how to parse the Parameters so that it can be embedded in sql statement
public JsonResult DeleteSelected(string [] Parameters)
{string strConn = "Data Source=localhost;Initial Catalog=Information;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(strConn);
string strSql = "DELETE FROM dbStudent where ID in";
SqlCommand myCommand = new SqlCommand(strSql, conn);
try
{
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(Parameters, JsonRequestBehavior.AllowGet);
}
what should be there in strSql..??
You can change your ajax post to be like that: (the contentType is important)
jQuery.ajax({
url: baseUrl + "DeleteSelected/",
type: 'Post',
dataType: 'json',
data: JSON.stringify(arrayOfID),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
jQuery("input:checkbox:checked").parents("tr").remove();
}
});
and your action method to be like that
public JsonResult DeleteSelected(int[] Parameters)
{
string strConn = "Data Source=localhost;Initial Catalog=Information;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(strConn);
var strSql = "DELETE FROM dbStudent where ID IN (" + String.Join(",", Parameters) + ")";
SqlCommand myCommand = new SqlCommand(strSql, conn);
try
{
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(Parameters, JsonRequestBehavior.AllowGet);
}
You can convert your array to int array
int[] myInts = Parameters.Select(int.Parse).ToArray();
Then
var query = "DELETE FROM dbStudent where ID IN (" +
String.Join(",", myInts ) + ")";
Related
I'm trying to send data to the controller using this AJAX call of type POST but it's sending null values to the controller. Through this code I want to make new records in the Microsoft Dynamics 365 CRM database.
var formdata = new FormData();
var rowCount = $(".newRow").length;
var projectarray = [];
var datearray = [];
var amountarray = [];
for (var i = 0; i < rowCount; i++) {
projectarray[i] = $("#ProjectType_" + i).val();
datearray[i] = $("#ClaimExpenseDate_" + i).val();
amountarray[i] = $("#Amount_" + i).val();
}
formdata.append("projectarray", projectarray);
formdata.append("datearray", datearray);
formdata.append("amountarray", amountarray);
$.ajax({
url: "#Url.Action("SetClaimDetails", "Claim")",
type: "POST",
data: formdata,
processData: false,
contenttype: false,
success: function (data) {
debugger;
window.location.href = "ess/claim";
alert("Submit Successful!");
},
error: function (err) {
window.location.href = "";
alert("Submit Failed!");
}
});
Here is my controller method which is storing null values instead of the values passed by the AJAX call. And because of this I'm not able to create new records in the database.
public ActionResult SetClaimDetails(string projectarray, string datearray, string amountarray)
{
try
{
Entity item = new Entity("bam_expenseclaims");
item["bam_expdate"] = Convert.ToDateTime(datearray);
item["bam_amount"] = amountarray;
item["bam_project"] = new EntityReference("new_project", Guid.Parse(projectarray));
globalService.Connection.Create(item);
}
catch (Exception ex)
{
XmlConfigurator.Configure();
ILog log = LogManager.GetLogger("TechnicalErrorAppender");
log.Error(string.Empty);
throw ex;
}
return View(Constant.CLAIMPATH);
}
Hy.
I want to make dropdownlist cascadin. select dropdownlist and send editorfor.but
Cannot set property 'value' of null error .
I would like to send a value to editorfor a value of dropdownlist.
Can you help me?
public JsonResult GetPrice(string log)
{
int id = 1;
HomeController.sqlconnection con = new HomeController.sqlconnection();
string FIRMA = "select t.FIRMA,t.donem FROM dbo.TBLFRM as t where t.ID=" + id + "";
SqlCommand cmd = new SqlCommand(FIRMA, con.connect());
SqlDataReader rdrr = cmd.ExecuteReader();
rdrr.Read();
string firma = rdrr["FIRMA"].ToString();
string donem = rdrr["DONEM"].ToString();
ExtreModel item = new ExtreModel();
item.ItemList = new List<ExtreModel>();
string urun = "select P.PRICE from DBO.LG_" + firma + "_PRCLIST as p,DBO.LG_" + firma + "_ITEMS as I WHERE P.CARDREF=I.LOGICALREF AND P.CARDREF=" + log + "";
SqlCommand cmdd = new SqlCommand(urun, con.connect());
SqlDataReader rdr = cmdd.ExecuteReader();
rdr.Read();
string PRICE = rdr[0].ToString();
con.connect().Close();
return Json(PRICE, JsonRequestBehavior.AllowGet);
}
<script>
$("#LOGI").change(function () {
var select = $(this);
var cityname = select.val();
if (cityname != "") {
$.ajax({
method: "GET",
url: '/Mobil/GetPrice' + '?log=' + cityname,
beforeSend: function () {
}
}).done(function (result) {
document.getElementById("fyt").value = result.PRICE;
});
} else {
}
});
</script>
The problem seems coming from this return statement:
return Json(PRICE, JsonRequestBehavior.AllowGet);
This statement returns plain string value which doesn't contain PRICE property, so result.PRICE contains null value and causing null property assignment error message. If you want to return the price value, simply use this inside done function:
document.getElementById("fyt").value = result;
or in jQuery version:
$('#fyt').val(result);
But if you still want to return PRICE property, specify it inside JSON data:
return Json(new { PRICE = PRICE }, JsonRequestBehavior.AllowGet);
And the AJAX callback should be look like this:
$("#LOGI").change(function () {
var cityname = $(this).val();
if (cityname != "") {
$.ajax({
type: "GET",
url: '/Mobil/GetPrice',
data: { log: cityname }
}).done(function (result) {
$("#fyt").val(result.PRICE); // now the price property should exist
});
} else {
// do something else
}
});
I hope developers can support me, I have minimal experience in the use of java script.
After investigating and several attempts, I was able to load a dropdownlist with data from a LINQ query and pass as a parameter the value of a textbox.
What I could not do is from the query Linq get two fields (Id and value) send them to the dropdownlist and show the value but after being able to use the Id of that field to be able to use it in a create, currently I can only show the value but I need the Id too.
View
#Html.TextBox("CP", "", new { #id = "txtCP", #onchange = "FillOption();", #placeholder = "Codigo Postal" })
#Html.DropDownList("Asentamientos", ViewBag.Drop as List<SelectListItem>)
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}
</script>
Controllers
public ActionResult Index()
{
List<SelectListItem> drop = new List<SelectListItem>
{
};
ViewBag.Drop = drop;
return View();
}
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select p.Asentamiento).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
I think of something like
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
but I do not know how the id and the value would be handled
Thanks
If I understand your question correctly, I think you need to name the fields of the object you are creating with the Linq expression, so that it would look something like this:
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { id = p.IdCodigoPostal, value = p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
Here are a few examples: https://code.msdn.microsoft.com/LINQ-to-DataSets-09787825#SelectAnonymousTypes1
Then you could access those fields from you javascript with data[i].id and data[i].value.
I hope this helps.
I suspect your issue is around pulling the data from the API result. You're setting the a new property in the ViewBag, then returning the ViewBag property. This really shouldn't be required, and you should instead just return your list, list so (Note: and SelectItemList has a property called "Items" which contains all items you've added):
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
This should return just a nice list of ListItems. You could also just change your jQuery to loop through the items property, like so:
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.Items.length; i++) {
$('#Asentamientos').append('<option value=' + data.Items[i].Value + '>' + data.Items[i].Text + '</option > ');
}
}
});
}
</script>
Thanks to all, the code works as follows
Controller
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { Value = p.IdCodigoPostal, Text= p.Asentamiento }).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}
My scenario is; I'm trying to do a live search feature for my ASP.net project. In the form, I have a description textbox where the user will type in the search and as the user types in anything, the GridView below filters the results accordingly. I have tried this on desktop applications and it's not much of a hassle but I recently dipped in on Web Applications. Any help would be appreciated. I'm sure there is an easy way to do this but I seem to be having trouble finding "that" way.
Below are what I tried already:
I have tried using onTextChanged property of the textbox but it only populates after the event request.
I have added a function using Ajax+ JQuery which calls the method but the gridview is not displaying the data.
enter code here
<script type="text/javascript">
$(function () {
GetCustomers();
});
$("[id*=TxtDescription]").live("keyup", function () {
GetCustomers();
});
function SearchTerm() {
return jQuery.trim($("[id*=TxtDescription]").val());
};
function GetCustomers() {
$.ajax({
type: "POST",
url: "frmDrugMaster.aspx/GetCustomers",
data: '{searchTerm: "' + SearchTerm() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
var row;
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Drugs");
alert(customers.length);
if (row == null) {
row = $("[id*=gvCustomers] tr:last-child").clone(true);
}
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
if (customers.length > 0) {
alert(customers.length);
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).html($(this).find("DR_Code").text());
$("td", row).eq(1).html($(this).find("DR_Description").text());
$("td", row).eq(2).html($(this).find("DR_UnitDose").text());
alert($("td", row).eq(0).html($(this).find("DR_Description").text()));
$("[id*=gvCustomers]").append(row);
$
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
} else {
var empty_row = row.clone(true);
$("td:first-child", empty_row).attr("colspan", $("td", row).length);
$("td:first-child", empty_row).attr("align", "center");
$("td:first-child", empty_row).html("No records found for the search criteria.");
$("td", empty_row).not($("td:first-child", empty_row)).remove();
$("[id*=gvCustomers]").append(row);
}
};
</script>
[WebMethod]
public static string GetCustomers(string searchTerm)
{
SqlConnection cn = new SqlConnection(WebConfigurationManager.ConnectionStrings["dbconn"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT a.DR_UNITDOSE, a.DR_CODE, a.DR_DESCRIPTION, a.DR_GENERIC1, a.DR_GENERIC2, a.DR_GENERIC3, a.DR_GENERIC4, a.DR_COSTPRICE, a.DR_SELLPRICE, a.DR_STATUS FROM DRUGMASTER a, DRUGCATEGORY b where a.DR_CATEGORY = b.DC_CODE and DR_DESCRIPTION='"+ searchTerm + "' ", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
DataTable dt = new DataTable();
dt.TableName = "Drugs";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds.GetXml();
}
I found a solution to this or atleast a sort to workaround it. I used AJAX + JQuery. I just created a web service for the particular page where the text change will be applied. The codes used are as follows. Hope this helps someone:
/*form*/
create a webform with a textbox and a gridview:
/*Add this script*/
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
script type="text/javascript">
$(function () {
$("[id*=txtCountry]").on("keyup", function () {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetCustomers",
data: '{searchTerm: "' + $(this).val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var row;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Customers");
if (row == null) {
row = $("[id*=gvCustomers] tr:last-child").clone(true);
}
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
if (customers.length > 0) {
$.each(customers, function () {
$("td", row).eq(0).html($(this).find("PD_FSTNM").text());
$("td", row).eq(1).html($(this).find("PD_GENDER").text());
$("[id*=gvCustomers]").append(row);
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
} else {
var empty_row = row.clone(true);
$("td:first-child", empty_row).attr("colspan", $("td", row).length);
$("td:first-child", empty_row).attr("align", "center");
$("td:first-child", empty_row).html("No records found for the search criteria.");
$("td", empty_row).not($("td:first-child", empty_row)).remove();
$("[id*=gvCustomers]").append(empty_row);
}
},
failure: function (response) { alert(response.d); },
});
});
});
</script>
/*C# Code*/
[System.Web.Services.WebMethod]
public static string GetCustomers(string searchTerm = "")
{
string strConnString = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string query = "SELECT * FROM patientdetails";
if (!string.IsNullOrEmpty(searchTerm))
{
query += " WHERE PD_FSTNM LIKE '" + searchTerm + "%'";
}
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds, "Customers");
return ds.GetXml();
}
This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});