checkbox with javascript && jQuery - javascript

I will display a view, when I click on checkbox
I tried like this, but not work,
I need your help to fix the problem
Models:
public class DisplayData
{
public bool ID { get; set; }
public DisplayData(bool ID)
{
this.ID = ID;
}
}
public class Element
{
public string Descripcion { get; set; }
}
HomeController:
public ActionResult Index()
{
DisplayData Display = new DisplayData(false);
return View(Display);
}
Index.cshtml:
#model AppTwitter.Models.DisplayData
<script src="#Url.Content("~/Scripts/myCheckbox.js")" type="text/javascript"></script>
#Html.CheckBoxFor(
x => x.ID,
new {
data_url = Url.Action("PartialDemo", "PartialDemo"),
id = "mycheckbox"
}
myCheckbox.js:
$(function () {
$('#mycheckbox').change(function () {
var data = {};
data[$(this).attr('name')] = $(this).is(':checked');
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: data,
success: function (result) {
}
});
});
});
PartialDemoController.cs
public ActionResult PartialDemo()
{
var element = new Element();
element.Descripcion = "Descripcion";
return View(element);
}
PartialDemo.cshtml:
#model AppTwitter.Models.Element
<div class="editor-label">
#Html.LabelFor(model => model.Descripcion )
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Descripcion )
#Html.ValidationMessageFor(model => model.Descripcion )
</div>
Thanks,

#Victor, Now i got the issue. The id that you are assigning to checkbox doesn't get worked because you are using #Html.CheckBoxFor(x => x.ID). in this case the id of checkbox is generating dynamically hence "mycheckbox" doesn't get worked. So Instead assigning a id assign a class i.e
#Html.CheckBoxFor(
x => x.ID,
new {
data_url = Url.Action("PartialDemo", "PartialDemo"),
#class = "mycheckbox"
}
)
and in javascript use below:
$(function () {
$('.mycheckbox').click(function () {
// your existing stuff
});
});
Hope this will solve the problem

Related

Javascript does not update value of a blazor component

I have a problem where I want to pass the value of a CK editor on to a Monaco editor. I can get the value from Monaco to CK but not the other way around. I can also see the value update while debugging but it does not seem to work somehow.
So what i want is when I type something in the CK editor and I press the button to switch to Monaco to have the value of the CK editor in the Monaco editor
This is the javasciprt :
function CkEditor(id, readonly, dotNetReference) {
CKEDITOR.replace(id, {
customConfig: '../ckeditor/config.js'
});
var editor = CKEDITOR.instances[id];
var editorId = editor.id;
var monacoEditor = document.getElementById("monaco_" + editor.name);
// Hide toolbar while loading
editor.on('loaded', () => {
document.getElementById(editorId + '_top').style.display = 'none';
});
editor.on('instanceReady', () => {
EnableCkEditor(id, readonly);
});
editor.on('change', () => {
var data = editor.getData();
if (data === '') {
data = null;
}
dotNetReference.invokeMethodAsync('EditorHasChanged', data);
});
editor.on('focus', (id) => {
editor.focusManager.focus();
document.getElementById(editorId + '_top').style.display = 'block';
editor.on('afterCommandExec', (event) => {
var commandName = event.data.name;
if (commandName === 'enableMonaco') {
if (monacoIsEnabled === false) {
document.getElementById(editorId + '_contents').style.display = 'none';
monacoEditor.classList.remove('monaco-wrapper');
monacoIsEnabled = true;
}
else {
editor.setData(monacoEditorData.value);
document.getElementById(editorId + '_contents').style.display = 'block';
monacoEditor.classList.add('monaco-wrapper');
monacoIsEnabled = false;
}
}
});
});
editor.on('blur', () => {
if (!monacoIsEnabled) {
document.getElementById(editorId + '_top').style.display = 'none';
}
});
}
function setCkEditorValue(value) {
monacoEditorData.value = value;
}
function CkEditorDestroy(id) {
var editor = CKEDITOR.instances[id];
editor.destroy();
delete editor;
}
function EnableCkEditor(id, readonly) {
var editor = CKEDITOR.instances[id];
if (editor) {
var editId = editor.id;
var editorBody = document.getElementById(editId + '_contents');
if (readonly === true) {
editorBody.classList.add('disabled_class');
}
else {
editorBody.classList.remove('disabled_class');
}
}
}
This is the component where it switches between Monaco and CK :
#inherits MarkupEditorComponent
#Value
<div id="wrapper">
<div class="ck-editor-wrapper">
<CkEditor Value="#Value" ValueChanged="#ValueChanged" Readonly="#Readonly" id="#Id"/>
</div>
<div class="monaco-wrapper" id="monaco_#Id">
<CodeEditor Value="#Value" ValueChanged="#ValueChanged" Readonly="#Readonly"/>
</div>
</div>
This is the CKEditor.razor
#inherits CkEditorComponent
<div id="wrapper">
<div class="ck-editor-wrapper">
<textarea #attributes="AdditionalAttributes"
id="#Id"
class="CssClass"
value="#Value"></textarea>
</div>
</div>
And as last the CKEditor.razor.cs
public class CkEditorComponent : BaseComponent
{
string _id = $"CKEditor{Guid.NewGuid().ToString().ToLower().Replace("-", string.Empty)}";
[Parameter]
public string Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
[Parameter]
public bool Readonly { get; set; }
[Parameter]
public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; }
[Parameter]
public string Id
{
get => _id;
set => _id = value;
}
protected override async Task OnInitializedAsync()
{
await EditorHasChanged(Value);
}
protected override async Task OnParametersSetAsync()
{
await EnableEditor(Readonly);
await base.OnParametersSetAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JsRuntime.InvokeVoidAsync("CkEditor", Id, Readonly, DotNetObjectReference.Create(this));
}
}
[JSInvokable(nameof(EditorHasChanged))]
public Task EditorHasChanged(string data)
{
Value = data;
ValueChanged.InvokeAsync(data);
return Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
JsRuntime.InvokeVoidAsync("CkEditorDestroy", Id);
base.Dispose(disposing);
}
private async Task EnableEditor(bool enabled)
{
await JsRuntime.InvokeVoidAsync("EnableCkEditor", Id, enabled);
}
}
You might need to invoke StateHasChanged() inside EditorHasChanged(string data). A similar issue here.

ASP.NET Framework MVC send Razor View data with ajax to the server after validation

I am doing an ASP.NET Framework MVC project and I need to send the combo boxes selected items from below partial view to the server with Jquery Ajax but these combo boxes must be validated at first and then the data must be sent in view model with Ajax to the action (DigestFile(ModelDto Mappings)) in the controller. My project parts is as below :
The partial view as below:
#using Web.Library.Bases;
#inherits Common.DataTransferObjects.Originals.ModelDto
#{
Layout = "";
List<(string Caption, bool IsAsigned, bool IsMandatory, bool IsSelected, string Name, string Title)> dataBaseFields = ViewBag.DataBaseFields;
int counter = 0;
}
<div id="Excel_B" class="editor-block">
#Html.Hidden("IsNotMatched")
<div class="block-label">
<p class="vertical-text">
تناظر فیلدها
</p>
</div>
<div class="block-content">
#foreach (var chlItem in dataBaseFields)
{
<div id="ExcelFields_G" class="editor-group ">
<div id="ExcelFields_L" class="editor-label mandatory">
<span class="MappingLabel">#chlItem.Caption :</span>
</div>
#switch (chlItem.Name)
{
case "RowNumber":
<div id="ExcelFields_A" class="editor-field ">
#Html.EditorFor(model => model.RowNumber, "ComboBox")
#Html.ValidationMessageFor(model => model.RowNumber)
</div>
break;
case "Name":
<div id="ExcelFields_B" class="editor-field ">
#Html.EditorFor(model => model.Name, "ComboBox")
#Html.ValidationMessageFor(model => model.Name)
</div>
break;
case "Family":
<div id="ExcelFields_C" class="editor-field ">
#Html.EditorFor(model => model.Family, "ComboBox")
#Html.ValidationMessageFor(model => model.Family)
</div>
break;
case "Code":
<div id="ExcelFields_D" class="editor-field ">
#Html.EditorFor(model => model.Code, "ComboBox")
#Html.ValidationMessageFor(model => model.Code)
</div>
break;
case "NationalCode":
<div id="ExcelFields_E" class="editor-field ">
#Html.EditorFor(model => model.NationalCode, "ComboBox")
#Html.ValidationMessageFor(model => model.NationalCode)
</div>
break;
default:
break;
}
</div>
}
</div>
#if (Model.IsNotMatched > 0)
{
<div class="DigestBut" title="Read File">
<a href="#" class="submitLink" onclick="DigestButtonClicked()">
Read File
</a>
</div>
}
</div>
</div>
The View Model as below:
namespace Common.DataTransferObjects.Originals
{
public class ModelDto
{
[Display(Name = "RowNumber")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string RowNumber { set; get; }
[Display(Name = "Name")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string Name { set; get; }
[Display(Name = "Family")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string Family { set; get; }
[Display(Name = "Code")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string Code { set; get; }
[Display(Name = "NationalCode")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string NationalCode { set; get; }
}
}
The Action is as below:
public ActionResult DigestFile(ModelDto Mappings)
{
....
}
Here is how you have to proceed in case you have many 'entries' to send in same time to save in your controller, but of course you can use it to send only one:
In your view:
<input id="Button1" type="button" value="button" onclick="SaveMe()" />
<script>
function SaveMe() {
// Get the value of your edit
var RowNumber0 = $("#RowNumber").val();
var Name0 = $("#Name").val();
var Family0 = $("#Family").val();
var Code0= $("#Code").val();
var NationalCode0= $("#NationalCode").val();
// Creat Object
var lineItems = new Object();
lineItems.Entrys = new Array();
// Example Filling your object...
lineItems.Entrys[0] = new Object({ RowNumber: RowNumber0, Name: Name0, Family: Family0, Code : Code0, NationalCode: NationalCode0 });
//lineItems.Entrys[1] = ... same logic for your other entries
// send by ajax to your controller and getting answer ...
$.ajax({
type: "POST",
url: "/Home/AjaxMethodDigestFile",
data: JSON.stringify({ Entrys: lineItems.Entrys }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) { alert(response.message); },
failure: function (response) { alert("failure"); },
error: function (response) { alert("error"); }
});
}
in your controller:
[HttpPost]
public JsonResult AjaxMethodDigestFile(ICollection<Common.DataTransferObjects.Originals.ModelDto > Entrys)
{
string message = "";
int counter = 0;
foreach (var entry in Entrys)
{
// How to use this data example
string RowNumber = entry.RowNumber;
string Name= entry.Name;
counter += 1;
message += "Saved " + ": " + counter + Constants.vbCrLf;
}
// The following lines are not necessary, it's just an example code to know what happen and return it to client side ...
if (counter > 0)
message = counter.ToString() + " Entrys received" + Constants.vbCrLf + message;
else
message = "no entrys";
var response = new { counter, message };
return Json(response);
}
EDIT:
About the validation
I don't know the library that you are using FoundationValidationMessages so can't help much with this, but I tried a classic way that work:
In Model:
[Required(ErrorMessage = "Required")]
public string RowNumber { set; get; }
In View:
#using (Html.BeginForm("Test2", "Home", FormMethod.Post))
{
...
#Html.EditorFor(model => model.RowNumber)
#Html.ValidationMessageFor(model => model.RowNumber)
...
}
And in your controller :
[HttpPost]
public ActionResult Test2(ModelDto um)
{
if (ModelState.IsValid)
{
return View(um);
}
else
{
return View();
}
}

Refresh ViewComponent in ASP.Net Core MVC View

I have a view component, EventsViewComponent, which is loaded in my Events view index.cshtml using the following lines of code:
<div id="events">
#await Component.InvokeAsync("Events", new { showPrevious = Model.ShowPrevious, showUpcoming = Model.ShowUpcoming })
</div>
I have two checkboxes added like this:
#Html.CheckBoxFor(m => m.ShowPrevious, new { id = "cbShowPrevious", onchange = "ReloadEvents()" })
#Html.CheckBoxFor(m => m.ShowUpcoming, new { id = "cbShowUpcoming", onchange = "ReloadEvents()" })
ReloadEvents() refers to a Javascript function in which I was hoping to refresh the EventsViewComponent with an Ajax call something like:
function ReloadEvents() {
$.ajax({
url: '#Url.Action("ReloadEvents", "Events")',
data: {
showPrevious: document.getElementById("cbShowPrevious").checked,
showUpcoming: document.getElementById("cbShowUpcoming").checked
},
success: DoThis()
})
}
function DoThis() {
const eventsDiv = document.getElementById('events');
eventsDic.innerHTML = //HTML from EventsViewComponent
}
But I don't seem to be able to get the HTML from the EventsViewComponent.
I have written the Default.cshtml for EventsViewComponent like this:
#{
List<Event> events = ViewData["Events"] as List<Event>;
if (events.Count > 0)
{
<table>
//event data from the model
</table>
}
}
The InvokeAsync method in EventsViewComponent is being hit, as is the ReloadEvents method in EventsController but I'm obviously misunderstanding something as I don't seem to be able to update the EventsViewComponent.
Please could someone advise if this is possible and how to go about achieveing it?
To get the HTML from the EventsViewComponent,you need to change like below:
success: function (data) {
$("#events").html(data);
}
Here is a whole working demo like below:
1.Model:
public class Event
{
public bool ShowPrevious { get; set; }
public bool ShowUpcoming { get; set; }
public string Data { get; set; }
}
2.ViewComponent:
public class EventsViewComponent : ViewComponent
{
List<Event> data = new List<Event>() {
new Event(){ ShowPrevious=true,ShowUpcoming=false,Data="aaa"},
new Event(){ ShowPrevious=false,ShowUpcoming=true,Data="bbb"},
new Event(){ ShowPrevious=false,ShowUpcoming=true,Data="ccc"},
};
public IViewComponentResult Invoke(bool showPrevious,bool showUpcoming)
{
if (showPrevious == true && showUpcoming == true)
{
ViewData["Events"] = data;
}
else if (showPrevious)
{
ViewData["Events"] = data.Where(u => u.ShowPrevious == true).ToList();
}
else if(showUpcoming)
{
ViewData["Events"] = data.Where(u => u.ShowUpcoming == true).ToList();
}
return View();
}
}
3.Controller:
public class HomeController : Controller
{
public IActionResult ReloadEvents(bool showPrevious, bool showUpcoming)
{
return ViewComponent("Events", new { showPrevious = showPrevious, showUpcoming = showUpcoming });
}
public IActionResult Index()
{
var model = new Event() { ShowPrevious = true, ShowUpcoming = true };
return View(model);
}
}
4.Index.cshtml:
#model Event
#Html.CheckBoxFor(m => m.ShowPrevious, new { id = "cbShowPrevious", onchange = "ReloadEvents()" })
#Html.CheckBoxFor(m => m.ShowUpcoming, new { id = "cbShowUpcoming", onchange = "ReloadEvents()" })
<div id="events">
#await Component.InvokeAsync("Events", new { showPrevious = Model.ShowPrevious, showUpcoming = Model.ShowUpcoming })
</div>
#section Scripts
{
<script>
function ReloadEvents() {
$.ajax({
url: '#Url.Action("ReloadEvents", "Home")',
data: {
showPrevious: document.getElementById("cbShowPrevious").checked,
showUpcoming: document.getElementById("cbShowUpcoming").checked
},
success: function (data) {
$("#events").html(data);
}
})
}
</script>
}
5.Default.cshtml(the view component Razor view):
#model Event
#{
List<Event> events = ViewData["Events"] as List<Event>;
if (events.Count > 0)
{
<table>
<tr>
<th>ShowPrevious</th>
<th>ShowUpcoming</th>
<th>Data</th>
</tr>
<tbody>
#foreach (var item in events)
{
<tr>
<td>#item.ShowPrevious</td>
<td>#item.ShowUpcoming</td>
<td>#item.Data</td>
</tr>
}
</tbody>
</table>
}
}
Result:
I have implemented such solution in one of my projects, check it out -> Refreshing .Net core MVC ViewComponent over AJAX

Kendo mvc grid with multiselect column. Row is null reference

I have two models with relationship "Many to Many", Books, Authors, and their context Library. All source files included correctly. Cannot set selected Authors to the cell(because row is null, so model cannot be set). There is using InCell editor. I will be glad to any ideas)
UPD: new error occurred when I add a new line
Unable to get property 'map' of undefined or null reference
Index.cs.html:(error in change function, second error in dataBound function)
#{
ViewBag.Title = "Home Page";
}
#(Html.Kendo().Grid<ManyToMany.Models.ViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(e => e.BookId).Visible(false);
columns.Bound(e => e.Pages);
columns.Bound(e => e.Genre);
columns.Bound(e => e.Publisher);
columns.Bound(e => e.Authors).ClientTemplate(
Html.Kendo().MultiSelect().Name("multi#=BookId#")
.DataTextField("AuthorName")
.DataValueField("AuthorId")
.BindTo((IEnumerable<ManyToMany.Models.Author>)ViewData["authors"]) /*TaskSecond.Models.ViewModel*/
.Events(e => e.Change("change"))
.ToClientTemplate().ToHtmlString()
);
columns.Command(command => command.Destroy()).Width(150);
})
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Filterable()
.Events(e => e.DataBound("dataBound"))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.Model(model =>
{
model.Id(p => p.BookId);
model.Field(p => p.Pages).DefaultValue(0);
model.Field(p => p.Genre).DefaultValue(0);
model.Field(p => p.Publisher).DefaultValue("");
model.Field(p => p.Authors).DefaultValue(
ViewData["defaultAuthors"] as ManyToMany.Models.Author);
})
.PageSize(5)
.Read(read => read.Action("Books_Read", "Grid"))
.Create(create => create.Action("Books_Create", "Grid"))
.Update(update => update.Action("Books_Update", "Grid"))
.Destroy(destroy => destroy.Action("Books_Destroy", "Grid"))
.ServerOperation(false))
)
<script type="text/javascript">
function dataBound(e) {
var grid = this;
grid.tbody.children().each(function () {
var dataitem = grid.dataItem(this),
row = $(this);
eval(row.find("script").html());
var multiSelect = $(this).find("select").data("kendoMultiSelect");
//here
multiSelect.value(dataitem.Authors.map(function (i) { return i.AuthorId }));
});
}
function change(e) {
//error is here
var row = this.element.closest("tr"),
model = $("#grid").data("kendoGrid").dataItem(row);
model.set("Authors", this.dataItems());
}
</script>
ViewModel.cs:
public class ViewModel
{
public ViewModel()
{
Authors = new List<Author>();
}
public int BookId { get; set; }
public string BookName { get; set; }
public int Pages { get; set; }
public Genre Genre { get; set; }
public string Publisher { get; set; }
[UIHint("AuthorsEditor")]
public List<Author> Authors { get; set; }
}
Try using - this.select() instead of this.element.closest in the change() javascript function. You may need to refine the below code to suit your requirements, but it would give you idea of what to change when you debug through:
var row = this.select();
if (row.length > 0 )
{
selectedRow = e.sender.select();
var item = e.sender.dataItem(selectedRow);
}

ASP.NET MVC 5 JsonResult & Ajax - MVC JQuery error

Thanks to #NikhilGhuse, which solution have been sent to me (please mark his answer). I can apply this solution to my data these are the results and the keys:
First of all my model need to send a List to the controller. This is my my function to send the List:
public List<VistaModelo> SegundaConsulta()
{
//Web.Config
Entities db = new Entities();
var consulta = from varLocal in db.LecturaContadorLuzAANDRES
group varLocal by varLocal.dispositivo into subconsulta
select subconsulta.OrderByDescending(t => t.unixtime).FirstOrDefault();
List<LecturaContadorLuzAANDRES> lista = consulta.ToList();
List<VistaModelo> listaVistaModelo = new List<VistaModelo>();
foreach (LecturaContadorLuzAANDRES b in lista)
{
VistaModelo objLista = b.pasaObjetoAVistaModelo();
listaVistaModelo.Add(objLista);
}
return listaVistaModelo;
}
Then in my controller I need two functions:
Consulta 6. Read the list and transform to JSON (you need: using Newtonsoft.Json; in the controller:
public JsonResult Consulta6()
{
var Consulta = new ConsultaContraBD();
List<VistaModelo> miSegundaConsulta = Consulta.SegundaConsulta();
return Json(miSegundaConsulta, JsonRequestBehavior.AllowGet); //El JsonRequest Behaviour permite que se devuelva información de JSON en un getRequest.
}
Consulta7. From this method I make the View:
public ActionResult Consulta7()
{
return View();
}
Finally I need Ajax into the script to read the information pass to method Consulta6. Note: Remember to load the packages json2.js and jquery-3.0.0.js
#{
ViewBag.Title = "Consulta7";
}
<script src="~/Script/jquery-3.0.0.js"></script>
<script src="~/Script/json2.js"></script>
<script type="text/javascript">
$(function () {
$('#btonLista').on("click", function (e) {
e.preventDefault();
$.ajax
({
url: '/Home/Consulta6/',
type: 'get',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
$('#ulLista').append("<li>" + item.consumo + "</li>")
});
}
});
});
});
</script>
<div>
<input type="button" id="btonLista" value="Click" name="" />
<ul id="ulLista"></ul>
</div>
The final result is a page where you click a button and returns the list.
<script type="text/javascript">
$(function ()
{enter code here
$('#btonLista').on("click", function (e)
{
e.preventDefault();
$.ajax
({
url: '/Home/Consulta52/',
type: 'GET',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
$('#ulLista').append("<li>"+item.consumo+"</li>")
});
}
});
});
});
</script>
My two controllers:
public ActionResult Consulta51()
{
return View();
}
public JsonResult Consulta52()
{
var Consulta = new ConsultaContraBD();
var miSegundaConsulta = Consulta.SegundaConsulta();
return Json(miSegundaConsulta.ToList(), JsonRequestBehavior.AllowGet);
}
/// My Sample Starts here
//Controller
namespace Sample.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public JsonResult Consulta52()
{
modelCS model = new modelCS();
List<Department> ds = model.getList();
return Json(ds, JsonRequestBehavior.AllowGet);
}
}
}
//Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<script src="../../scripts/jquery-2.1.4.js" type="text/javascript">
</script>
<script src="../../scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#btonLista').on("click", function (e) {
e.preventDefault();
$.ajax
({
url: '/Home/Consulta52/',
type: 'get',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
$('#ulLista').append("<li>" + item.DepartmentName + "</li>")
});
}
});
});
});
</script>
<div>
<input type="button" id="btonLista" value="Click" name="" />
<ul id="ulLista">
</ul>
</div>
And My Model Class goes like this
public class modelCS
{
string constr = "Data Source=.;Initial Catalog=test1;Integrated Security=True";
List<Department> newDept = new List<Department>();
public List<Department> getList()
{
SqlConnection con = new SqlConnection(constr);
// SqlCommand cmd = new SqlCommand("select * from Department", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Department", con);
DataSet ds = new DataSet();
da.Fill(ds);
var td = ds.Tables[0];
// List<Department> newDept = new List<Department>();
foreach (DataRow t in td.Rows)
{
newDept.Add(new Department() { DepartmentId = (int)t.ItemArray[0], DepartmentName = t.ItemArray[1].ToString() });
}
return newDept;
//List<string> list = listT
}
}
Department class
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}

Categories