Delete from session at specific Index Entity Framework - asp.net-mvc

I have a form which adds bill details, like in the screenshot:
In this form person first add the entries that are stored in the session through this code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string nameValueInsert, string nameValueSubmit, CreateBillViewModel model, int? Patient_id)
{
int count = 0;
var button = nameValueInsert ?? nameValueSubmit;
if (button == "Insert")
{
if (Session["templist"] == null)
{
List<PatientViewModel> lst = new List<PatientViewModel>();
lst.Add(new PatientViewModel()
{ Count = count,
PatientAppointmentID = Int32.Parse(Request.Form["PatientAppointmentID"]),
// BillNo = Request.Form["BillNo"],
Amount = double.Parse(Request.Form["Amount"]),
Description = Request.Form["Description"]
});
Session["templist"] = lst;
}
else
{
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
lst.Add(new PatientViewModel()
{
Count = lst.Count + 1,
PatientAppointmentID = Int32.Parse(Request.Form["PatientAppointmentID"]),
// BillNo = Request.Form["BillNo"],
Amount = double.Parse(Request.Form["Amount"]),
Description = Request.Form["Description"]
});
Session["templist"] = lst;
}
}
else
{
if (ModelState.IsValid)
{
string username = "";
HttpCookie cookie = HttpContext.Request.Cookies["AdminCookies"];
if (cookie != null)
{
username = Convert.ToString(cookie.Values["UserName"]);
}
tblPatientBill patientbill = new tblPatientBill();
patientbill.PatientAppointmentID = model.PatientAppointmentID;
// patientbill.BillNo = model.ID;
patientbill.Amount = model.AmountTotal;
patientbill.Description = model.Note;
patientbill.Discount = model.Discount;
patientbill.CreatedAt = model.CreatedAt;
patientbill.CreatedBy = username;
patientbill.is_active = true;
db.tblPatientBills.Add(patientbill);
db.SaveChanges();
int PatientBill_ID = Convert.ToInt32(patientbill.ID);
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
if (lst != null)
{
tblPatientBillDetail billdetail = new tblPatientBillDetail();
foreach (var item in lst)
{
billdetail.PatientBillID = PatientBill_ID;
billdetail.Amount = item.Amount;
billdetail.CreatedAt = DateTime.UtcNow;
billdetail.CreatedBy = username;
billdetail.Description = item.Description;
billdetail.is_active = true;
db.tblPatientBillDetails.Add(billdetail);
db.SaveChanges();
}
Session.Clear();
}
return RedirectToAction("Print", new { Billid = #PatientBill_ID });
}
}
return View(model);
}
}
}
and after when done with all the entries upon submit all the record is saved into the database.
Now what I am trying to do is if while entering the entries if the user want to delete any row he should be able to delete it from session and upon finalizing the remaining data should go into the DB for which i am doing the following approach:
Id is going to controller through Ajax call:
$("body").on("click", "#tblBills .Delete", function () {
if (confirm("Do you want to delete this row?")) {
var row = $(this).closest("tr");
var Id = row.find("span").html();
console.log("Id");
$.ajax({
type: "POST",
url: "/Session_Delete",
data: '{ID: ' + Id+ '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("hello");
$("#test").remove();
}
});
}
});
and in the controller, I am removing the row from session like this:
[HttpPost]
public ActionResult DeleteBillSession(int ID)
{
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
lst.Remove(lst.FirstOrDefault(t => t.Count == ID));
Session["templist"] = lst;
return Json(new { success = "Valid" }, JsonRequestBehavior.AllowGet);
}
The problem is it is removing the row from session but it is deleting the last in the sequence not the one which i have selected to be deleted.

If someone gets into the same situation the issue is resolved like this:
View:
<table id="tblBills" class="table table-bordered table-striped table-hover js-basic-example dataTable">
<tr>
<th style="width:100px">Patient Appointmnet ID</th>
<th style="width:100px">Amount</th>
<th style="width:150px">Description</th>
<th style="width:40px">Action</th>
</tr>
#{
double? AmountTotal = 0;
if (Session["templist"] != null)
{
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
int count = 0;
foreach (var o in lst)
{
<tr>
<td class="Count" style="display:none">
<span>#count</span>
</td>
<td class="AppointmentID">
<span>#o.PatientAppointmentID</span>
</td>
<td class="Amount">
<span>#o.Amount</span>
</td>
<td class="Description">
<span>#o.Description</span>
</td>
<td>
<a class="Delete" href="javascript:;">Delete</a>
</td>
</tr>
AmountTotal += #o.Amount;
count++;
}}
else
{
<tr>
<td colspan="4"> No Data Found</td>
</tr>
}
}
</table>
Ajax Call:
$("body").on("click", "#tblBills .Delete", function () {
if (confirm("Do you want to delete this row?")) {
var row = $(this).closest("tr");
var id= row.find("span").html();
$.ajax({
type: "POST",
url: "/Session_Delete",
data: '{ID: ' + id+ '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#tblBills").load(window.location + " #tblBills");
}
});
}
});
Controller Method:
[HttpPost]
public ActionResult DeleteBillSession(int ID)
{
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
lst.RemoveAt(ID);
Session["templist"] = lst;
// return new EmptyResult();
return Json(new { success = "Valid" }, JsonRequestBehavior.AllowGet);
}

Related

elements inside #if condition in CSHTML page is not displayed even when the condition is true

This is my CSHTML page.
<div>
<table cellpadding="8">
<tr>
<th>File Path</th>
<td>#Html.TextBoxFor(Model => Model.returnFilename, new { id = "filepath" })</td>
</tr>
</table>
#if (Model != null)
{
<table cellpadding="8">
<tr>
<th>File Names</th>
<td>
#Html.DropDownListFor(Model => Model.getFileNamesList, new SelectList(Model.getFileNamesList, "getFilepath", "getFileNames"), " -- Select File --", htmlAttributes: new { style = "width: 200px;" })
</td>
</tr>
</table>
}
</div>
<script type="text/javascript">
$(function () {
console.log("in script");
$("[id$=filepath]").on('change', function () {
$.ajax(
{
type: 'POST',
dataType: 'JSON',
url: '/Home/LoadFiles',
data: { filePath: $(this).val() }
})
})
})
</script>
The JavaScript call is made when something is entered in the text box and return. This will call a controller method and fetch the details for a dropdown.
Controller method.
public ActionResult LoadFiles(string filePath, FeatureDisplayListModel getFileName)
{
ModelState.Clear();
string errorMessage = "";
GetFilesModel objFileNames = new GetFilesModel();
try
{
string[] fileEntries = Directory.GetFileSystemEntries(filePath);
foreach (string fileName in fileEntries)
{
if (getFileName.getFileNamesList == null)
{
getFileName.getFileNamesList = new List<GetFilesModel>();
}
string trimFileName = Path.GetFileName(fileName);
objFileNames.getFileNames = trimFileName;
objFileNames.getFilepath = fileName;
getFileName.getFileNamesList.Add(objFileNames);
}
getFileName.isFileName = true;
}
catch (Exception ex)
{
errorMessage = "NO TAG FOUND";
//featAndChannel.returnFilename = featureID + " - " + childFeatureID + " " + errorMessage;
return View("Index", getFileName);
}
return View("ConfigChecker", getFileName);
}
When the details are fetched and returned back to view. The #if condition encapsulating the dropdown is not working. Though it gets into the #if block it is not displaying the dropdown inside it.
If you want to get data from action with ajax,you can try to return List<GetFilesModel> type data to ajax,and then adding html to dropdown with the data:
action:
public List<GetFilesModel> LoadFiles(string filePath, FeatureDisplayListModel getFileName)
{
ModelState.Clear();
string errorMessage = "";
GetFilesModel objFileNames = new GetFilesModel();
try
{
string[] fileEntries = Directory.GetFileSystemEntries(filePath);
foreach (string fileName in fileEntries)
{
if (getFileName.getFileNamesList == null)
{
getFileName.getFileNamesList = new List<GetFilesModel>();
}
string trimFileName = Path.GetFileName(fileName);
objFileNames.getFileNames = trimFileName;
objFileNames.getFilepath = fileName;
getFileName.getFileNamesList.Add(objFileNames);
}
getFileName.isFileName = true;
}
catch (Exception ex)
{
errorMessage = "NO TAG FOUND";
//featAndChannel.returnFilename = featureID + " - " + childFeatureID + " " + errorMessage;
return getFileName.getFileNamesList ;
}
return getFileName.getFileNamesList ;
}
ajax:
$(function () {
console.log("in script");
$("[id$=filepath]").on('change', function () {
$.ajax(
{
type: 'POST',
dataType: 'JSON',
url: '/Home/LoadFiles',
data: { filePath: $(this).val() },
success: function (data) {
var items = '';
$("#getFileNamesList").empty();
$.each(data, function (i, FileNamesList) {
items += "<option value='" + FileNamesList.getFilepath + "' selected>" + FileNamesList.getFileNames + "</option>";
});
$('#getFileNamesList').html(items);
},
})
})

Infinite Scroll - ASP.NET Core MVC

We are trying to implement infinite scroll in data grid in an ASP.NET Core MVC application. Searched a lot but could not find a good solution. Has any one used infinite scroll in data grid in an ASP.NET Core MVC . If so can you provide any guidance
I faced the same problem. Here is my solution. It works on nearly any table:
InfinityScroll.js
function InfinitiySroll(iTable, iAction, iParams) {
this.table = iTable; // Reference to the table where data should be added
this.action = iAction; // Name of the conrtoller action
this.params = iParams; // Additional parameters to pass to the controller
this.loading = false; // true if asynchronous loading is in process
this.AddTableLines = function (firstItem) {
this.loading = true;
this.params.firstItem = firstItem;
// $("#footer").css("display", "block"); // show loading info
$.ajax({
type: 'POST',
url: self.action,
data: self.params,
dataType: "html"
})
.done(function (result) {
if (result) {
$("#" + self.table).append(result);
self.loading = false;
}
})
.fail(function (xhr, ajaxOptions, thrownError) {
console.log("Error in AddTableLines:", thrownError);
})
.always(function () {
// $("#footer").css("display", "none"); // hide loading info
});
}
var self = this;
window.onscroll = function (ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
//User is currently at the bottom of the page
if (!self.loading) {
var itemCount = $('#' + self.table + ' tr').length - 1;
self.AddTableLines(itemCount);
}
}
};
this.AddTableLines(0);
}
Here a from Visual Studio scaffold view - a little bit modified
TestData.cshtml
#model IEnumerable<Infinity_Scroll.Models.TestData>
#{
ViewData["Title"] = "TestData";
}
<h1>TestData</h1>
<table id="anyTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Field1)
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section Scripts {
<script src="~/js/InfinitiySroll.js"></script>
<script>
var infinityScroll = new InfinitiySroll("anyTable", "/home/_TestData", { sortOrder: "ascending", searchString: "3" });
</script>
}
The generating of the table rows is moved into a PartialView:
_TestData.cshtml
#model IEnumerable<Infinity_Scroll.Models.TestData>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Field1)
</td>
</tr>
}
And here is the Controller part:
...
private const int BATCH_SIZE = 50;
public IActionResult TestData()
{
return View();
}
[HttpPost]
public IActionResult _TestData(string sortOrder, string searchString, int firstItem = 0)
{
List<TestData> testData = new List<TestData>();
// Generate test data
for (int i = 1; i < 500; i++)
{
testData.Add(new TestData() { Id = i, Field1 = "This is row " + i.ToString() });
}
// Sort and filter test data
IEnumerable<TestData> query;
if (sortOrder.ToLower() == "descending")
{
query = testData.OrderByDescending(m => m.Field1);
}
else
{
query = testData.OrderBy(m => m.Field1);
}
if (!String.IsNullOrEmpty(searchString)) query = query.Where(m => m.Field1.Contains(searchString));
// Extract a portion of data
var model = query.Skip(firstItem).Take(BATCH_SIZE).ToList();
if (model.Count() == 0) return StatusCode(204); // 204 := "No Content"
return PartialView(model);
}
The model:
TestData.cs
namespace Infinity_Scroll.Models
{
public class TestData
{
public int Id { get; set; }
public string Field1 { get; set; }
}
}
You can download a simple Visual Studio example here: https://github.com/ThomasBrockmann/InfinityScroll

my list variable array missing after click button

I don't have DB, instead DB I have to list array, I have a table, and when I want Edit details of Driver, I click 'edit', after that display change to page with details, after that I can change details and click save button, my problem that after clicking button 'save', my array list miss, I not very good in MVC, but I try my best! if somebody sees what I do wrong, please tell me and explain, thank you
that my controller
public class DriverTaxiController : Controller
{
static List<Drivers> Driver = new List<Drivers>();
public static int numLine = -1;
// GET: DriverTaxi
public ActionResult List()
{
Driver.Add(new Drivers() { Line = 1, NumberLicens = "123456", FirstName = "Evgeny", LastName = "Ryvkin", PhoneNumber = "0546819725", StartWork = "12/10/17", DateCheckEyes = "13/10/17"});
Driver.Add(new Drivers() { Line = 2, NumberLicens = "123457", FirstName = "Moshe", LastName = "Kohen", PhoneNumber = "0546819725", StartWork = "12/10/17", DateCheckEyes = "13/10/17" });
Driver.Add(new Drivers() { Line = 3, NumberLicens = "123458", FirstName = "Dana", LastName = "Multy", PhoneNumber = "0546819725", StartWork = "12/10/17", DateCheckEyes = "13/10/17" });
ViewBag.Drivers = Driver;
return View();
}
public ActionResult MyAction(int id=0)
{
for(int i = 0; i < Driver.Count; i++)
{
if(Driver[i].Line == id)
{
ViewBag.nl = Driver[i].NumberLicens;
ViewBag.fn = Driver[i].FirstName;
ViewBag.ln = Driver[i].LastName;
ViewBag.phone = Driver[i].PhoneNumber;
ViewBag.start = Driver[i].StartWork;
ViewBag.eye = Driver[i].DateCheckEyes;
ViewBag.line = Driver[i].Line;
}
}
numLine = id;
return View();
}
[HttpPost]
public ActionResult Update()
{
if (ModelState.IsValid)
{
numLine--;
Driver[numLine].NumberLicens = Request.Form["NumberLicens"];
Driver[numLine].FirstName = Request.Form["FirstName"];
Driver[numLine].LastName = Request.Form["LastName"];
Driver[numLine].PhoneNumber = Request.Form["PhoneNumber"];
Driver[numLine].StartWork = Request.Form["StartWork"];
Driver[numLine].DateCheckEyes = Request.Form["DateCheckEyes"];
return View("List2");
}
else
{
return View("MyAction");
}
}
that my View Edit, when I click the button, my parameters not saved in my list, I don't understand why
#using (Html.BeginForm("Update", "DriverTaxi"))
{
#Html.TextBoxFor(Model => Model.NumberLicens, new { #Value = #ViewBag.nl }) #Html.ValidationMessageFor(x => x.NumberLicens)
<br />
#Html.TextBoxFor(Model => Model.FirstName, new { #Value = #ViewBag.fn })
<br />
#Html.TextBoxFor(Model => Model.LastName, new { #Value = #ViewBag.ln })
<br />
#Html.TextBoxFor(Model => Model.PhoneNumber, new { #Value = #ViewBag.phone })
<br />
#Html.TextBoxFor(Model => Model.StartWork, new { #Value = #ViewBag.start })
<br />
#Html.TextBoxFor(Model => Model.DateCheckEyes, new { #Value = #ViewBag.eye })
<br />
#Html.HiddenFor(Model => Model.Line)
<input type="submit" value="Save" />
#Html.ValidationSummary()
}
that my Table
<table class="table table-bordered table-responsive table-hover">
<tr>
<th>No.</th>
<th>Number Licens</th>
<th>Full Name</th>
<th>Phone Number</th>
<th>Start Work</th>
<th>Date Cheking the Eyes</th>
<th>Address</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (Drivers p in ViewBag.Drivers)
{
<tr>
<td>#p.Line</td>
<td>#p.NumberLicens</td>
<td>#p.FirstName #p.LastName </td>
<td>#p.PhoneNumber</td>
<td>#p.StartWork</td>
<td>#p.DateCheckEyes</td>
<td>
#Html.ActionLink("Edit", "MyAction", "DriverTaxi", new { id = p.Line }, null)
</td>
<td>addres</td>
<td>email</td>
<td><input id="Button2" type="submit" value="Delete" name="#p.NumberLicens" /></td>
</tr>
}`enter code here`
and that my error
enter image description here
Just add your ViewBag assignment to each of your actions that render view. Something like this:
public ActionResult MyAction(int id=0)
{
for(int i = 0; i < Driver.Count; i++)
{
if(Driver[i].Line == id)
{
ViewBag.nl = Driver[i].NumberLicens;
ViewBag.fn = Driver[i].FirstName;
ViewBag.ln = Driver[i].LastName;
ViewBag.phone = Driver[i].PhoneNumber;
ViewBag.start = Driver[i].StartWork;
ViewBag.eye = Driver[i].DateCheckEyes;
ViewBag.line = Driver[i].Line;
}
}
numLine = id;
ViewBag.Drivers = Driver; //TODO
return View();
}
[HttpPost]
public ActionResult Update()
{
if (ModelState.IsValid)
{
numLine--;
Driver[numLine].NumberLicens = Request.Form["NumberLicens"];
Driver[numLine].FirstName = Request.Form["FirstName"];
Driver[numLine].LastName = Request.Form["LastName"];
Driver[numLine].PhoneNumber = Request.Form["PhoneNumber"];
Driver[numLine].StartWork = Request.Form["StartWork"];
Driver[numLine].DateCheckEyes = Request.Form["DateCheckEyes"];
ViewBag.Drivers = Driver; //TODO
return View("List2");
}
else
{
ViewBag.Drivers = Driver; //TODO
return View("MyAction");
}
}

dropdown load on selection of other dropdown

I have the dropdown trigger an ajax post that sends the selected value of country dropdown .
model class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_4___A_Registration_Form.Models
{
public class ModelServices
{
private readonly MyCompanyEntities entities = new MyCompanyEntities();
public IEnumerable<Country> GetCountryList()
{
return entities.Countries.ToList();
}
public IEnumerable<countryState> GetStateByCountry(int CountryID)
{
return entities.countryStates.Where(s => s.CountryId == CountryID).ToList();
}
public IList<EmployeeRegInfo> GetAllEmployeeList()
{
var myQuery = (from e in entities.Employees
join c in entities.Countries on e.Country equals c.CountryId
join s in entities.countryStates on e.State equals s.StateId
select new EmployeeRegInfo()
{
Id = e.Id,
Emp_ID = e.Emp_ID,
Dept = e.Dept,
Name = e.Name,
CountryName = c.County,
StateName = s.State,
City = e.City,
Mobile = e.Mobile
});
return myQuery.ToList();
}
public bool IsEmpAlreadyExist(string EMP_CODE)
{
bool IsRecordExist = false;
var result = (from t in entities.Employees
where t.Emp_ID == EMP_CODE
select t).SingleOrDefault();
if (result != null)
{
IsRecordExist = true;
}
return IsRecordExist;
}
public void AddNewEmployee(Employee emp)
{
entities.Employees.Add(emp);
entities.SaveChanges();
}
}
}
create.cshtml
#model MVC_4___A_Registration_Form.Models.EmployeeRegInfo
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#ViewBag.ErrorMsg
<table>
<tr>
<td>
#Html.LabelFor(model => model.Emp_ID)
</td>
<td>#Html.EditorFor(model => model.Emp_ID)
#Html.ValidationMessageFor(model => model.Emp_ID)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Name)
</td>
<td>#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Dept)
</td>
<td>#Html.EditorFor(model => model.Dept)
#Html.ValidationMessageFor(model => model.Dept)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Country)</td>
<td>#Html.DropDownList("Country", ViewBag.Country as SelectList, new { Styles = "width:300px" })</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.State)
</td>
<td>
<select id="State" name="State" style="width: 200px"></select>
#Html.ValidationMessageFor(model => model.State)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.City)</td>
<td>#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Mobile)</td>
<td>#Html.EditorFor(model => model.Mobile)
#Html.ValidationMessageFor(model => model.Mobile)
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Add Employee" /></td>
</tr>
</table>
}
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var url = "/ManageEmployee/GetStatesByCountry";
var countryID = $("#Country").val();
$.post(url, { countryID: countryID }, function (data) {
$("#State").empty();
var items;
$.each(data, function (i, states) {
items += "<option value=" + states.StateId + ">" + states.State + "</option>";
});
$("#State").html(items);
});
});
});
</script>
controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_4___A_Registration_Form.Models;
namespace MVC_4___A_Registration_Form.Controllers
{
public class ManageEmployeeController : Controller
{
ModelServices model = new ModelServices();
//
// GET: /ManageEmployee/
public ActionResult Index()
{
IList<EmployeeRegInfo> empList = new List<EmployeeRegInfo>();
empList = model.GetAllEmployeeList();
return View(empList);
}
public ActionResult Create()
{
IEnumerable<Country> country;
country = model.GetCountryList();
ViewBag.Country = new SelectList(country, "CountryId", "County", "CountryId");
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
bool checkEmpCodeExist = false;
checkEmpCodeExist = model.IsEmpAlreadyExist(collection["Emp_ID"]);
if (!checkEmpCodeExist)
{
try
{
Employee emp = new Employee();
emp.Emp_ID = collection["Emp_ID"];
emp.Name = collection["Name"];
emp.Dept = collection["Dept"];
emp.Country = Convert.ToInt32(collection["Country"]);
emp.State = Convert.ToInt32(collection["State"]);
emp.City = collection["City"];
emp.Mobile = collection["Mobile"];
model.AddNewEmployee(emp);
return RedirectToAction("Index");
}
catch (Exception ex)
{
return RedirectToAction("Create");
}
}
else
{
ViewBag.ErrorMsg = "Employee Code Already Exist";
return RedirectToAction("Create");
}
}
public JsonResult GetStatesByCountry(int id)
{
var states = model.GetStateByCountry(id);
return Json(states, JsonRequestBehavior.AllowGet);
}
}
}
I want to load state dropdown on selection of country dropdown.But i am unable to do this.
Please help to load state dropdown on selection of country dropdown.
I want to load state dropdown on selection of country dropdown.But i am unable to do this.
Please help to load state dropdown on selection of country dropdown.
Hey I got the answer
some change in ajax code and controller
$(document).ready(function () {
$("#Country").change(function () {
var url = "/ManageEmployee/GetStatesByCountry";
var countryID = $("#Country").val();
$.ajax({
url: url,
data: { id: countryID },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#State").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
});
[HttpPost]
public JsonResult GetStatesByCountry(string id)
{
int ids = Convert.ToInt32(id);
var states = model.GetStateByCountry(ids);
SelectList obgcity = new SelectList(states, "StateId", "State", 0);
return Json(obgcity);
}

I'm implementing handsontable, where i need show the excel data in handsontable

I need to show the data in handsontable from excle sheet, But I got struck up in the middle, any one please help me here.
My controller code
public ActionResult Index()
{
return View();
}
public ActionResult GetJsonData(FormCollection formCollection)
{
var usersList = new List<User>();
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.First();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var user = new User();
user.FirstName = workSheet.Cells[rowIterator, 1].Value.ToString();
user.LastName = workSheet.Cells[rowIterator, 2].Value.ToString();
usersList.Add(user);
}
}
}
}
return View("GetJsonData",usersList);
}
Index view
<h2>Index</h2>
#using (Html.BeginForm("GetJsonData", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>File:</td>
<td>
<input type="file" name="UploadedFile" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="Submit" value="Submit" id="btnsave" />
</td>
</tr>
</table>
}
<div id="example1" class="hot handsontable htColumnHeaders"></div>
<script type="text/javascript">
$('#btnsave').click(function () {
var url = '/Home/GetJsonData';
$.get(url,
null,
function (data) {
debugger;
var container = document.getElementById('#example1');
var hot = new Handsontable(container, {
data: data,
rowheader: true,
colheader: true
});
});
});
</script>
GetJsonData view
<div id="example1" class="hot handsontable htColumnHeaders"></div>
<script type="text/javascript">
$(document).ready(function () {
var url = '/Home/GetJsonData';
$.get(url,
null,
function (data) {
var container = document.getElementById('#example1');
var hot = new Handsontable(container, {
data: data,
rowheader: true,
colheader: true
});
debugger;
});
});
</script>
have resolved this issue.
function UploadExcel() {
var formData = new FormData();
var totalFiles = document.getElementById("Uplaod").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("Uplaod").files[i];
formData.append("Document", file);
}
$.ajax({
url:"/Home/UpoadFile",
type: "POST",
dataType: "JSON",
data: formData,
contentType: false,
processData: false,
//data: JSON.stringify(oInvoice),
//contentType: "application/json; charset=utf-8",
//async: false,
success: function (result) {
debugger;
if (result != null)
{
//var data2 = result,
// container = document.getElementById('example1'),
// hot1;
//hot1 = new Handsontable(container, {
// data: JSON.parse(JSON.stringify(data2))
//});
//document.addEventListener("DOMContentLoaded", function() {
var data = result,
example1 = document.getElementById('example1'),
settings1,
emailValidator;
emailValidator = '^[^##\\s]+##([^##\\s]+\\.)+[^##\\s]+$';
emailValidator=function(value,callback)
{
setTimeout(function () {
if (/.+##.+/.test(value)) {
callback(true);
}
else {
callback(false);
}
}, 10);
}
settings1={
data: data,
colHeaders: ['FirstName','LastName','Email'],
columns:[
{data:'FirstName'},
{data:'LastName'},
{ data: 'Email', validator: emailValidator, allowInvalid: false }
]
} ;
var hot = new Handsontable(example1, settings1);
//function bindDumpButton()
//{
// if (typeof Handsontable === "undefined") {
// return;
// }
// //Handsontable.Dom.AddEvent(document.body, 'click', function (e) {
// // var element = e.target || e.srcElement;
// // if (element.nodeName == "BUTTON" && element.name == 'dump') {
// // var name = element.getAttribute('data-dump');
// // var instance = element.getAttribute('data-instance');
// // var hot = window[instance];
// // console.log('data of ' + name, hot.getData());
// // }
// //});
//}
//bindDumpButton();
// });
}
else {
// alert("Something Seems wrong. try agin afterwards");
}
},
error: function (err) {
}
});
}

Resources