Data binding kendo grid asp.net mvc - kendo-ui

Hi guys i need your help !!!!. Is it possible to update data from kendo grid using stored procedure in sql server?
I mean: #Html.Kendo.Grid ->>> Method wich executes stored procedure ; <<<-
All examples that i looked for use "Entity Framework Data Model" for binding data to kendo grid. but i want to use my own class to connect to the database.
public class LessonsDep
{
public int LesId { get; set; }
public int Activated { get; set; }
public string TaskTable { get; set; }
}
public class LessonsBusinessLayer
{
public void changeLessons(LessonsDep lessons){
string connectionString = ConfigurationManager.ConnectionStrings["nisa1415"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("dep.edidBiology",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter();
paramId.ParameterName = "#LesId";
paramId.Value = LessonNameClass.stcLesId;
cmd.Parameters.Add(paramId);
SqlParameter paramActivated = new SqlParameter();
paramActivated.ParameterName = "#Activated";
paramActivated.Value = lessons.Activated;
cmd.Parameters.Add(paramActivated);
SqlParameter paramTaskTable = new SqlParameter();
paramTaskTable.ParameterName = "#TaskTable";
paramTaskTable.Value = lessons.TaskTable;
cmd.Parameters.Add(paramTaskTable);
con.Open();
cmd.ExecuteNonQuery();
}
}
}

Do you have any problems using what you proposed?
I mean I'm not using Entity in any of my projects ( I use NHibernate) and I think you can use any ORM or other technic instead to read/save/update/delete data.
Of course you have to get data and return it in the same format kendo grid requires.
public virtual JsonResult Read([DataSourceRequest] DataSourceRequest request)
{
//for example use your code code here for SELECT operation to get
//all the elements you want. Assign to List<> list variable and voila
return Json(list.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

Related

Returning ADO.Net query as JSON array from controller

I have the following database class which uses ADO.NET to connect to a SQL database without any models. I use the GetData method to return a serialized json string which I then convert in the ActionResult get request in my controller a shown below. The issue is I am first returning a DataTable object from the ADO.NET query which is then serialized to a string using a third party nuget package Newtonsoft which is converted to a json/application type in my controller. Is there no way to achieve these results with less steps or third party plugins?
When using a model approach with the DB such as Entity Framework I was able to use Ok() method to convert to JSON format for my EF query. This was so simple but I hated the idea of keeping models that I will never use so I switched to ADO.NET. I am still learning both ADO.NET and ASP.NET Core so any help is appreciated.
Database class
public String GetData(String connectionString, string str, params IDataParameter[] sqlParams)
{
int rows = -1;
DataTable objResult = new DataTable();
try
{
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(connectionString))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(str, myCon))
{
if (sqlParams != null)
{
foreach (IDataParameter para in sqlParams)
{
myCommand.Parameters.Add(para);
}
}
myReader = myCommand.ExecuteReader();
objResult.Load(myReader);
myReader.Close();
myCon.Close();
}
}
}
catch (Exception ex)
{
}
return JsonConvert.SerializeObject(objResult);
}
Controller:
public ActionResult DatatableLoad()
{
//Since ADO.NET returns a datatable we serialize it first in GetData()
//We have parameters here just in case we want to use them
string query = "select * from dbo.UserAccountsTbl WHERE USERNAME=#UserName;";
var parameters = new IDataParameter[]
{
new SqlParameter("#UserName", "SB")
};
String jsonResult = db.GetData(connectionString, query, parameters);
return Content(jsonResult, "application/json");
}
To return the output of a query in JSON format you need to do this:
return Json(jsonResult, JsonRequestBehavior.AllowGet);
jsonResult is the output list of the Executed Query.

mvc dropdownlist not showing data value

I'm having an issue displaying data from the database into drop-downlist.
controller
TowinsEntities db = new TowinsEntities();
public ActionResult TMakes()
{
//T_Make make_db = new Models.T_Make();
ViewBag.carMaker = new SelectList(db.T_Make, "Make");
return View();
}
view
#Html.DropDownList("carMaker", "Select Make")
model
public partial class T_Make
{
public string Make { get; set; }
}
The output of a view is:
You need to overload your DropDownList with the string field names you want for value/display. You're only passing the model and selected value. I guess you'd use Make for both value and display (though, most people would use an ID for a value)
ViewBag.carMaker = new SelectList(db.T_Make, "Make","Make");
https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.selectlist.-ctor?view=aspnet-mvc-5.2#System_Web_Mvc_SelectList__ctor_System_Collections_IEnumerable_System_String_System_String_

90% there, how to replace table reference with SP in listboxfor

Using Data Entity Framework, I created added my database.
I have a table called Droptest, see models entry :
namespace DropMenu4FEB2018_FINAL.Models
{
using System;
using System.Collections.Generic;
public partial class DropTest
{
public string DisplayList { get; set; }
public string DisplayIndex { get; set; }
}
}
CONTROLLER CODE :
Public action Create ()
{
DROPMENUEntities db = new DROPMENUEntities();
List<DropTest> list = db.DropTests.ToList();
ViewBag.DropTestList = new SelectList(list, "DisplayIndex", "DisplayList");
Return view ();
}
VIEW CODE :
#Html.LabelFor(model => model.Car, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Car, ViewBag.DropTestList as SelectList, "--SELECT ONE--", new { #class = "form-control"
#Html.ValidationMessageFor(model => model.Car, "", new { #class = "text-danger" })
The above controller and view code is working.
Now, I decided it would be more flexible if I used a stored procedure to return the contents of the table (to support filtered output in the future). I created the stored procedure (basic at this stage), which I called DisplayCars in SSMS, and it was named by data entity framework as DisplayCars_Result
In the models you can view the stored procedure entry :
namespace DropMenu4FEB2018_FINAL.Models
{
using System;
public partial class DisplayCars_Result
{
public string DisplayList { get; set; }
public string DisplayIndex { get; set; }
}
}
I am unable to determine the syntax to replace the table reference with the stored procedure reference from within the controller method Create (the changes below don’t work)
public ActionResult Create()
{
//DROPMENUEntities db = new DROPMENUEntities();
//List<DropTest> list = db.DropTests.ToList();
//ViewBag.DropTestList = new SelectList(list, "DisplayIndex", "DisplayList");
DROPMENUEntities DROPMENUEntities = new DROPMENUEntities();
List<DisplayCars_Result> list = DROPMENUEntities.DisplayCars.ToList();
ViewBag.DisplayCars = new SelectList(list, "DisplayIndex", "DisplayList");
return View();
}
Any help will be gratefully received. Thanks.
This was a simple fix to the List statement, that is, postfix the stored procedure name DisplayCars with (), see below:
public ActionResult Create()
{
DROPMENUEntities db = new DROPMENUEntities();
List<DisplayCars_Result> list = db.DisplayCars().ToList();
ViewBag.DisplayCars = new SelectList(list, "DisplayIndex", "DisplayList");
return View();
}
Now its working as expected. Cheers.

ASP.NET MVC 4 Want to populate dropdown list from database

I am new guy in ASP.NET MVC 4. I want to populate dropdownlist from database table BO where Column name is Id, Code, Name, OrgId. I want to bind two Code & Namecolumn's data to DataTextfield and Id column Data to DataValueField of dropdown. I have created code for this which are as follows BUT ITS NOT RETURNING DATA FROM TABLE and var BOList is remain empty :
my connectionstring is
<add name="iRegDBContext"
connectionString="Data Source=****;Initial Catalog=iReg;User ID=**;Password=****;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
My Controller class :
public class iRegController : Controller
{
private iRegDBContext l_oDbBO = new iRegDBContext();
// GET: /iReg/
public ActionResult PopulatejQgrid()
{
var BOList = l_oDbBO
.BO
.ToList()
.Select(d => new SelectListItem
{
Value = d.Id.ToString(),
Text = d.Name + "[ " + d.Code + " ]"
});
ViewBag.BOData = new SelectList(BOList, "Value", "Text");
return View();
}
}
My Model class :
public class BO
{
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class iRegDBContext : DbContext
{
public DbSet<BO> BO { get; set; }
}
My cshtml class :
#model MvciReg.Models.BO
#{
ViewBag.Title = "PopulatejQgrid";
}
#using (Html.BeginForm())
{
<fieldset>
BO :
#Html.DropDownList("BOData")
<p>
<input type="submit" value="Go" />
</p>
</fieldset>
}
I really don't know where I am going wrong. I developed my code from reference of following link Click here . Kindly suggest correction in code ...
UPDATE: I tried following Matt Bodily's code in my controller and what I see is code is not fetching data from database and that code is
public ActionResult populatejQgrid()
{
ViewBag.BOData = GetDropDown();
return View();
}
public static List<SelectListItem> GetDropDown()
{
List<SelectListItem> ls = new List<SelectListItem>();
var lm = from m in db.BOs //fetch data from database
select m;
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.Name, Value = temp.Id.ToString() });
}
return ls;
}
In Controller :
#Html.DropDownList("BOData", (List<SelectListItem>)ViewBag.BOData)
But when I saw value of ls through watch it always show me Count = 0 but its not giving me any error.
I found something new this problem. When I kept mouse pointer over var lm; it shows me query and in query table name in FROM clause is not that one in my SQL database. My SQL table name is BO and in query it is taking BOes. I don't know from where this name is coming. I think this is the main cause of all this problem So How I overcome this??
First Create a BO list for Dropdownlist in VIEW
#{
var Bolst= Model.BO.Select(cl => new SelectListItem
{
Value = cl.Value.ToString(),
Text = cl.Text== null ? String.Empty : cl.Text
});
}
#(Html.DropDownList("sampleDropdown", BOlst, "-----Select-----"))
In Controller:
return View(BOlst); // why use Viewbag when directly pass it to view
from what I see in your code you are creating the select list and setting the ViewBag.BOData on the controller.
So in order to render it on the view you should do this
#Html.DropDownList(ViewBag.BOData)
instead of
#Html.DropDownList("BOData")
Regarding the access to the database are you trying to use "code first" in an existing database?
If you are you need to override the context constructor like this
public class iRegDBContext : DbContext
{
  public iRegDBContext()
     :base("Name= iRegDBContext")
   {
   }
}
see this link http://msdn.microsoft.com/en-us/data/jj200620.aspx
Hope it helps.
try building your dropdown this way
#Html.DropDownList(x => x.Selected, PathToController.GetDropDown())
and then in your controller
public static List<SelectListItem> GetDropDown()
{
List<SelectListItem> ls = new List<SelectListItem>();
lm = (call database);
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.name, Value = temp.id });
}
return ls;
}
Hopefully this helps
I recently had this issue also and managed to get it working using Viewbag. You will need to make it fit your Db tables but it works and is quite simple.
Populating Drop Down Box with Db Data

trouble in converting Generic List coming from a WCF Service to a DataTable

I am confused on how can I use generic methods to parse generic list into datatable/dataset. My setup:
1. I have a class Customers defined in WCF Service Library.
namespace Wcf.Sample.ServiceLibrary
{
public class Customers
{
public string ID = string.Empty;
public string CompanyName = string.Empty;
public string ContactName = string.Empty;
}
}
2. I use this class to return a generic list from my OperationContract.
namespace Wcf.Sample.ServiceLibrary
{
[ServiceContract]
public interface ICustomerService
{
[OperationContract]
List<Customers> GetAllCustomers();
}
}
3. Consume WCF Service in web client page. On button click I populate the GridView with the list returned from GetAllCustomers(). This works perfectly fine.
GridView1.DataSource = client.GetAllCustomers();
GridView1.DataBind();
4. Now the issue is, for some reason (sort/paging function) I want to actually convert the returned generic list into a datatable. To do so, I have a method that returns me a datatable which I want to bind to a GridView. Here are the methods:
public static DataTable ConvertTo<T>(System.Collections.Generic.List<T> genericList)
{
//create DataTable Structure
DataTable dataTable = CreateTable<T>();
Type entType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in genericList)
{
DataRow row = dataTable.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
dataTable.Rows.Add(row);
}
return dataTable;
}
public static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable dataTable = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
dataTable.Columns.Add(prop.Name, prop.PropertyType);
}
return dataTable;
}
I am not sure how to call this function? How can I specify the as Customers class which is actually in a webservice? Totally lost. I would appreciate if someone can guide me on the following code, how to make it work.
GridView1.DataSource = ConvertTo<???>(client.GetAllCustomers());
I was able to resolve this issue by modifing the WCF Service itself (although I was reluctant to do so). I modified the GetAllCustomers method to return a datatable instead of generic type. In the service itself, I am converting the generic type into datatable using the same methods:
public static DataTable ConvertTo<T>(System.Collections.Generic.List<T> genericList)
{
//create DataTable Structure
DataTable dataTable = CreateTable<T>();
Type entType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in genericList)
{
DataRow row = dataTable.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
dataTable.Rows.Add(row);
}
return dataTable;
}
public static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable dataTable = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
dataTable.Columns.Add(prop.Name, prop.PropertyType);
}
return dataTable;
}
Another thing that I noticed is that the following line
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
would always returned null for my type. This was due to the fact that I didn't have any get/set methods in Customers class. I created get/set methods in Customer class and everything worked like a charm.
Thanks to everyone who helped and those who tried to help :)

Resources