Populate gridview from database using javascript - javascript

is there a javascript where I can populate a gridview from the database? For example is there a javascript for this code?
gvRFPCorpCode is the name of my gridview
private void fillCorpCode()
{
DataSet ds = new DataSet();
data.gRowId = this.txtROWID.Text;
ds = data.GetCorpCode();
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
this.gvRFPCorpCode.DataSource = ds.Tables[0];
this.gvRFPCorpCode.DataBind();
}
}
}
ds = data.GetCorpCode(); is equal to this:
public DataSet GetCorpCode()
{
DataSet ds = new DataSet();
SqlParameter[] sqlParam = new SqlParameter[]
{
new SqlParameter("#RowId",sRowId)
};
if (this.InitDataLayerObject() == true)
{
ds = this.ExecuteQuery("dbo.sp_ESS_RFP_GetCorpCode", sqlParam);
}
return ds;
}
It's a stored procedure, here is my stored procedure "dbo.sp_ESS_RFP_GetCorpCode"
ALTER PROCEDURE [dbo].[sp_ESS_RFP_GetCorpCode]
-- Add the parameters for the stored procedure here
#RowId varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #xml as xml
select
#xml =convert(xml,CORPCODE)
from Tbl_ESS_Request_For_Payment_Save
where ROWID=#RowId
select
tbl.col.value('CorpCode[1]', 'varchar(100)') as CorpCode,
tbl.col.value('Amount[1]', 'varchar(100)')as Amount
from #xml.nodes('/NewDataSet/Table1') tbl(col)
END
What I want is to have a javascript equivalent to private void fillCorpCode to populate it on my gridview, BTW, You might ask why I need a javascript if i already have a code in c#, It's because of some process in my program and it is difficult to explain. So please help me on this one, thank you in advance!

do like this
function getJSONData(selVal, callbackName) {
selVal = encodeURI(selVal);
var formdata = { };// any data you want to pass as input
$.ajax({
type: "POST",
url: "aspx",
data: formdata,
cache: false,
success: function (data) {
callbackName(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error in processing data !!' + thrownError);
},
async: false
});
}
function createTable() {
mytable = $('<table Class="table table-striped table-bordered table-hover"></table>').attr({ id: "basicTable" });
// alert(rowData);
var rowobj = JSON.parse(rowData);
// To populate header
var firstrow;
var firstrow = $('<tr></tr>').appendTo(mytable);
$('<td></td>').text('Entity Name').appendTo(firstrow);
$('<td></td>').text('Attribute Name').appendTo(firstrow);
$('<td></td>').text(' Value').appendTo(firstrow);
// To populate rows
$.each(rowobj, function (i, obj) {
$('<td valign="middle"></td>').text(obj.ParentName).appendTo(row);
$('<td valign="middle"></td>').text(obj.ParentName1).appendTo(row);
$('<td valign="middle"></td>').text(obj.ParentName2).appendTo(row);});
}
//C# method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static string Mymethod(string entityName, string entityType, string filterValues)
{
List<MasterFields> fields = null;
ServiceWrapper<ILOSService>.Perform(svcClient =>
{
fields = getfields();
});
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(fields);
return output;
}

Related

ASP.NET web app with Javascript - properly populate database columns

Creating a CRUD app in ASP.NET with C#, Javascript and SQL Server 2017.
The database table has three columns, Country, CountryCode and CountryCodeId that I'm attempting to populate with a create function (yes I'm aware of the relational design flaw here - that's outside of the scope of the question)...
I have an enum class that looks like this:
public enum Country
{
[Description("Afghanistan")] AFG = 1,
[Description("Ă…land Islands")] ALA = 2,
[Description("Albania")] ALB = 3,
}
I have a dropdown menu in the UI which displays the names of the country as shown in the Description piece above. Let's say the chosen value of the dropdown is Afghanistan. What I need to do upon execution of the create function is populate the Country column of the database with Afghanistan, the CountryCodecolumn with AFG and the CountryCodeId column with 1.
My Javascript skills are what are the most lacking, and I can only get the CountryCodeId to work, out of the three. This is my JS code - the question marks are where I'm lost:
async function newRecord(form) {
var record = {};
record.countryCodeId = $('#country').val();
record.countryCode = $("???").val();
record.country = $("???").val();
var response = await fetch(`${endpoint}api/record`, {
method: 'POST',
crossDomain: true,
cache: 'no-cache',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(record)
});
EDIT 1: as requested, here is the C# Insertfunction:
public bool Insert(Record record)
{
SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("Production"));
connection.Open();
using (connection)
{
string query = "INSERT INTO [dbo].[Table]" +
"([Country]" +
",[CountryCode]" +
",[CountryCodeId]")
"VALUES " +
"(#Country" +
",#CountryCode" +
",#CountryCodeId")";
return connection.Execute(query, record) > 0;
}
}
EDIT 2:
Controller action method for Insert:
[HttpPost]
public JsonResult Insert(Record record)
{
try
{
bool result = _repository.Insert(record);
return new JsonResult(new OperationResult { Success = true });
}
catch (Exception ex)
{
return new JsonResult(new OperationResult { Success = false, Error = ex.Message });
}
}
Try this: -
using System.ComponentModel;
.
.
void ProcessCountry(string countryCode)
{
Country country;
// i.e. countryCode = "AFG"
if (Enum.TryParse(countryCode, out country))
{
string description = null;
try
{
FieldInfo fieldInfo = country.GetType().GetField(country.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])
fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
description = ((attributes.Length != 0) ?
attributes[0].Description :
country.ToString());
}
catch (System.NullReferenceException)
{
}
finally
{
if (string.IsNullOrEmpty(description))
{
description = "Unknown";
}
}
int value = Convert.ToInt32(country);
Console.Write($"countryCode: {countryCode}, description: {description}, value: {value}");
}
}
The FieldInfo/DescriptionAttribute stuff pulls the description out of the System.ComponentModel.Description attribute, and as you've given your enum values INT values then you can parse them as Int.

How to fix Ajax call "The parameters dictionary contains a null entry........."

I'm trying to send my data via ajax call to the controller but I check all my code I debug it all values are filled but it continuously shows me this error. event its also show me ON MVC call As Well
The parameters dictionary contains a null entry for parameter 'BrandId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Forms(System.Collections.Generic.IEnumerable1[System.Web.HttpPostedFileBase], System.String, Int32, Int32, Boolean, Int32)'in'AdminDevVersion.Controllers.HomeController'`. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
i have already debugged the code and I have checked if all the values are filled.
My Ajax Code
function uploadSubmitHandler() {
var PName = $("#ProductName").val();
var Category = $("#CategoryDropDown").val();
var Brand = $("#BrandDropDown").val();
var SubCategory = $("#SubCategory").val();
var ProductDescription = $('textarea.textarea-editor').val();
var NewOROldRadio = $("input[name='ProductStatus']:checked").val();
if (state.fileBatch.length !== 0) {
var data = new FormData();
for (var i = 0; i < state.fileBatch.length; i++) {
data.append('files', state.fileBatch[i].file, state.fileBatch[i].fileName);
}
data.append('ProductName', PName);
data.append('CategoryId', Category);
data.append('BrandId', Brand);
data.append('IsNewStatus', NewOROldRadio);
data.append('SubCategoryId', SubCategory);
data.append('Description', ProductDescription);
$.ajax({
type: 'POST',
url: options.ajaxUrl,
data: data,
cache: false,
contentType: false,
processData: false
});
}
}
Controller Code
[HttpPost]
public ActionResult Forms(IEnumerable<HttpPostedFileBase> files, String ProductName, int CategoryId, int BrandId, bool IsNewStatus, int SubCategoryId)
{
List<string> FileNames = new List<string>();
string ImageName = null;
TblProduct InsertProduct = new TblProduct();
if (ModelState.IsValid == true)
{
InsertProduct.Name = ProductName;
InsertProduct.IsActive = IsNewStatus;
InsertProduct.BrdId = BrandId;
InsertProduct.CatId = SubCategoryId;
InsertProduct.Image = ImageName;
InsertProduct.Created = DateTime.Now;
InsertProduct.IsActive = true;
_RepoProduct.Insert(InsertProduct);
_RepoProduct.Save();
TblProRelImg RelatedImages = new TblProRelImg();
foreach (HttpPostedFileBase file in files)
{
string _path = System.IO.Path.Combine(Server.MapPath("~/Content/Images/"), file.FileName);
file.SaveAs(_path);
if (file == files.First())
{
ImageName = file.FileName.ToString();
}
else
{
RelatedImages.PrdID = InsertProduct.ID;
RelatedImages.Image = file.FileName;
_ReporRelatedImages.Insert(RelatedImages);
_ReporRelatedImages.Save();
}
FileNames.Add(file.FileName);
}
ViewBag.CategoryId = Logics.Category();
ViewBag.BrandInfo = new SelectList(DbContext.TblBrands, "Id", "Name");
}
return View();
}
I have expected to send data to the controller
parse your BrandId to int like blow and append to your data
parseInt(Brand)

Ajax returning datatable always going in error part in asp.net

I return list of values in a datatable and that I want to fill in success part of ajax function in dropdownlist. Till return dt I get all the values properly but after that it goes in error part. Below is what I tried.
Ajax function
function getMZONEWithState(evt) {
var ddlState = $('#ContentPlaceHolder1_ddlState').val();
var ddlMaintenanceZone = $("#ddlMaintenanceZone");
ddlMaintenanceZone.empty().append('<option selected="selected" value="0" disabled = "disabled">State Loading...</option>');
$.ajax({
type: "POST",
url: "Dashboard.aspx/GetMaintZone",
data: JSON.stringify({ ddlState: ddlState }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
And in code behind:-
[WebMethod]
public static DataTable GetMaintZone(string ddlState)
{
DataTable dt = new DataTable();
try
{
CommonDB ObjCommon = new CommonDB();
dt = ObjCommon.GetMZONE(ddlState);
return dt;
}
catch (Exception)
{
throw;
}
}
Why it always goes in error part I don't understand ?? Please suggest If I am going wrong anywhere.
You can't return DataTable directly from your [WebMethod] like this. You need to convert your DataTable to JSON before sending to cleint.
Change your server side code like following.
[WebMethod]
public static string GetMaintZone(string ddlState)
{
DataTable dt = new DataTable();
try
{
CommonDB ObjCommon = new CommonDB();
dt = ObjCommon.GetMZONE(ddlState);
return DataTableToJSON(dt);
}
catch (Exception)
{
throw;
}
}
public static string DataTableToJSON(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in table.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
}

Ajax call to webmethod gives ERROR 500

I'm a beginner and I want to use ajax to load some data from database to dropdownlist when another dropdownlist selected index in changed
but I'm getting nothing but 500 error
My jquery ajax code
function ddlGroups() {
var s = $("#Content_ddlGroups").find("option:selected").prop("value");
$.ajax({
method: "GET",
contentType: "application/json; charset=utf-8",
//url is the path of our web method (Page name/function name)
url: "../panels/admin/AddProject.aspx/getSubgroups",
data: { Id: s },
dataType: "json",
//called on jquery ajax call success
success: function (result) {
$('#Content_SubGroups').empty();
$.each(result.d, function (key, value) {
$("#Content_ddlGroups").append($("<option></option>").val(value.GroupID).html(value.Title));
});
},
//called on jquery ajax call failure
error: function ajaxError(result) {
alert(result.status + ' : ' + result.statusText);
}
});
};
and my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt());
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}
What is the problem??
The jQuery is not the problem here. The 500 error is thrown by the server, so you should review the log of your c# code to find out the details about it and be able to narrow the causes.
In your AJAX Call actually 500 error caused beacuse you have passed
Id:s instead of Id having some digits. Ex. Id : 5.
I see your code if you passed string as a id so in your server side method
you are trying to convert that string to int.That actually causes the 500 error.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt()); // Here You have convert string to Int that's why you got 500 Error.
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}

MVC 3 .NET Fill fields dynamically

I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}

Categories

Resources