FullCalendar not updating Database using asp.net webforms mssql ajax jquery - c#

I am trying to use a fullcalendar module to see various events. So far only events from the database get populated onto the fullcalendar but any edit or delete or add operation do not get reflected in the database
I have used masterpage and this page is the contentpage
so the master page has style sheets and javascript files such as
<title>ASP.NET FullCalendar</title>
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/jquery-ui.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.css" rel="stylesheet" />
..
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.js"></script>
<script src="scripts/calendarscript.js" type="text/javascript"></script>
my aspx file:EventManagement.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div id="calendar">
</div>
<div id="updatedialog" style="font: 70% 'Trebuchet MS', sans-serif; margin: 50px;display: none;"
title="Update or Delete Event">
<table class="style1">
<tr>
<td class="alignRight">
Name:</td>
<td class="alignLeft">
<input id="eventName" type="text" size="33" /><br /></td>
</tr>
<tr>
<td class="alignRight">
Description:</td>
<td class="alignLeft">
<textarea id="eventDesc" cols="30" rows="3" ></textarea></td>
</tr>
<tr>
<td class="alignRight">
Start:</td>
<td class="alignLeft">
<span id="eventStart"></span></td>
</tr>
<tr>
<td class="alignRight">
End: </td>
<td class="alignLeft">
<span id="eventEnd"></span><input type="hidden" id="eventId" /></td>
</tr>
<tr>
<td>
<div class="ui-dialog-buttonset">
<asp:Button ID="Button1" runat="server" Text="Update" ></asp:Button>
<asp:Button ID="Button2" runat="server" Text="delete" ></asp:Button>
</div>
</td>
</tr>
</table>
</div>
<div id="addDialog" style="font: 70% 'Trebuchet MS', sans-serif; margin: 50px;" title="Add Event">
<table class="style1">
<tr>
<td class="alignRight">
Name:</td>
<td class="alignLeft">
<input id="addEventName" type="text" size="33" /><br /></td>
</tr>
<tr>
<td class="alignRight">
Description:</td>
<td class="alignLeft">
<textarea id="addEventDesc" cols="30" rows="3" ></textarea></td>
</tr>
<tr>
<td class="alignRight">
Start:</td>
<td class="alignLeft">
<span id="addEventStartDate" ></span></td>
</tr>
<tr>
<td class="alignRight">
End:</td>
<td class="alignLeft">
<span id="addEventEndDate" ></span></td>
</tr>
</table>
</div>
<div runat="server" id="jsonDiv" />
<input type="hidden" id="hdClient" runat="server" />
my code behind file: EventManagement.aspx.cs
public partial class EventManagement : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//this method only updates the title and description
//this is called when an event is clicked on the calendar
[System.Web.Services.WebMethod(true)]
public static string UpdateEvent(CalendarEvent cevent)
{
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(cevent.id))
{
if (CheckAlphaNumeric(cevent.name) && CheckAlphaNumeric(cevent.description))
{
EventDAO.updateEvent(cevent.id, cevent.name, cevent.description);
return "updated event with id:" + cevent.id + " update title to: " + cevent.name +
" update description to: " + cevent.description;
}
}
return "unable to update event with id:" + cevent.id + " title : " + cevent.name +
" description : " + cevent.description;
}
//this method only updates start and end time
//this is called when a event is dragged or resized in the calendar
[System.Web.Services.WebMethod(true)]
public static string UpdateEventTime(ImproperCalendarEvent improperEvent)
{
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(improperEvent.id))
{
EventDAO.updateEventTime(improperEvent.id, improperEvent.title, improperEvent.description,
Convert.ToDateTime(improperEvent.start),
Convert.ToDateTime(improperEvent.end),
improperEvent.allDay); //allDay parameter added for FullCalendar 2.x
return "updated event with id:" + improperEvent.id + " update start to: " + improperEvent.start +
" update end to: " + improperEvent.end;
}
return "unable to update event with id: " + improperEvent.id;
}
//called when delete button is pressed
[System.Web.Services.WebMethod(true)]
public static String deleteEvent(int id)
{
//idList is stored in Session by JsonResponse.ashx for security reasons
//whenever any event is update or deleted, the event id is checked
//whether it is present in the idList, if it is not present in the idList
//then it may be a malicious user trying to delete someone elses events
//thus this checking prevents misuse
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(id))
{
EventDAO.deleteEvent(id);
return "deleted event with id:" + id;
}
return "unable to delete event with id: " + id;
}
//called when Add button is clicked
//this is called when a mouse is clicked on open space of any day or dragged
//over mutliple days
[System.Web.Services.WebMethod(true)]
public static int addEvent(ImproperCalendarEvent improperEvent)
{
CalendarEvent cevent = new CalendarEvent()
{
name = improperEvent.title,
description = improperEvent.description,
start = Convert.ToDateTime(improperEvent.start),
end = Convert.ToDateTime(improperEvent.end),
allDay = improperEvent.allDay
};
if (CheckAlphaNumeric(cevent.name) && CheckAlphaNumeric(cevent.description))
{
int key = EventDAO.addEvent(cevent);
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null)
{
idList.Add(key);
}
return key; //return the primary key of the added cevent object
}
return -1; //return a negative number just to signify nothing has been added
}
private static bool CheckAlphaNumeric(string str)
{
return Regex.IsMatch(str, #"^[a-zA-Z0-9 ]*$");
}
}
my JsonResponse.ashx file
public class JsonResponse : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
DateTime start = Convert.ToDateTime(context.Request.QueryString["start"]);
DateTime end = Convert.ToDateTime(context.Request.QueryString["end"]);
List<int> idList = new List<int>();
List<ImproperCalendarEvent> tasksList = new List<ImproperCalendarEvent>();
//Generate JSON serializable events
foreach (CalendarEvent cevent in EventDAO.getEvents(start, end))
{
tasksList.Add(new ImproperCalendarEvent {
id = cevent.id,
title = cevent.name,
start = String.Format("{0:s}", cevent.start),
end = String.Format("{0:s}", cevent.end),
description = cevent.description,
allDay = cevent.allDay,
});
idList.Add(cevent.id);
}
context.Session["idList"] = idList;
//Serialize events to string
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(tasksList);
//Write JSON to response object
context.Response.Write(sJSON);
}
public bool IsReusable {
get { return false; }
}
}
the CalendarEvent.cs class which has all properties regarding events
public class CalendarEvent
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public DateTime start { get; set; }
public DateTime end { get; set; }
public bool allDay { get; set; }
}
my dataaccess class-EventDAO.cs that speaks to the database
public class EventDAO
{
//change the connection string as per your database connection.
//string connectionString = ConfigurationManager.AppSettings["DBConnString"];
private static string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
//this method retrieves all events within range start-end
public static List<CalendarEvent> getEvents(DateTime start, DateTime end)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT id,name, description, eventstart, eventend, isFullDay,IsHalfDay,IsQuatDay FROM Events where eventstart between #start AND #end or eventend between #start and #end", con);
cmd.Parameters.AddWithValue("#start", start);
cmd.Parameters.AddWithValue("#end", end);
//cmd.Parameters.Add("#start", SqlDbType.DateTime).Value = start;
//cmd.Parameters.Add("#end", SqlDbType.DateTime).Value = end;
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
events.Add(new CalendarEvent() {
id = Convert.ToInt32(reader["id"]),
name = Convert.ToString(reader["name"]),
description = Convert.ToString(reader["description"]),
start = Convert.ToDateTime(reader["eventstart"]),
end = Convert.ToDateTime(reader["eventend"]),
allDay = Convert.ToBoolean(reader["isFullDay"])
});
}
}
return events;
//side note: if you want to show events only related to particular users,
//if user id of that user is stored in session as Session["userid"]
//the event table also contains an extra field named 'user_id' to mark the event for that particular user
//then you can modify the SQL as:
//SELECT event_id, description, title, event_start, event_end FROM event where user_id=#user_id AND event_start>=#start AND event_end<=#end
//then add paramter as:cmd.Parameters.AddWithValue("#user_id", HttpContext.Current.Session["userid"]);
}
//this method updates the event title and description
public static void updateEvent(int id, String title, String description)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE Events SET name=#title, description=#description WHERE id=#event_id", con);
cmd.Parameters.Add("#title", SqlDbType.VarChar).Value = title;
cmd.Parameters.Add("#description", SqlDbType.VarChar).Value= description;
cmd.Parameters.Add("#event_id", SqlDbType.Int).Value = id;
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
//this method updates the event start and end time ... allDay parameter added for FullCalendar 2.x
public static void updateEventTime(int id,string title,string description, DateTime start, DateTime end, bool allDay)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE Events SET name=#title,description=#description,eventstart=#event_start, eventend=#event_end, isFullDay=#all_day WHERE id=#event_id", con);
cmd.Parameters.Add("#event_start", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("#event_end", SqlDbType.DateTime).Value = end;
cmd.Parameters.Add("#event_id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("#all_day", SqlDbType.Bit).Value = allDay;
cmd.Parameters.AddWithValue("#title", title);
cmd.Parameters.AddWithValue("#description", description);
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
//this method deletes event with the id passed in.
public static void deleteEvent(int id)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("DELETE FROM Events WHERE (id = #event_id)", con);
cmd.Parameters.Add("#event_id", SqlDbType.Int).Value = id;
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
//this method adds events to the database
public static int addEvent(CalendarEvent cevent)
{
//add event to the database and return the primary key of the added event row
//insert
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Events(name, description, eventstart, eventend, isFullDay) VALUES(#title, #description, #event_start, #event_end, #all_day)", con);
cmd.Parameters.Add("#title", SqlDbType.VarChar).Value = cevent.name;
cmd.Parameters.Add("#description", SqlDbType.VarChar).Value = cevent.description;
cmd.Parameters.Add("#event_start", SqlDbType.DateTime).Value = cevent.start;
cmd.Parameters.Add("#event_end", SqlDbType.DateTime).Value = cevent.end;
cmd.Parameters.Add("#all_day", SqlDbType.Bit).Value = cevent.allDay;
int key = 0;
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
//get primary key of inserted row
cmd = new SqlCommand("SELECT max(id) FROM Events where name=#title AND description=#description AND eventstart=#event_start AND eventend=#event_end AND isFullDay=#all_day", con);
cmd.Parameters.Add("#title", SqlDbType.VarChar).Value = cevent.name;
cmd.Parameters.Add("#description", SqlDbType.VarChar).Value = cevent.description;
cmd.Parameters.Add("#event_start", SqlDbType.DateTime).Value = cevent.start;
cmd.Parameters.Add("#event_end", SqlDbType.DateTime).Value = cevent.end;
cmd.Parameters.Add("#all_day", SqlDbType.Bit).Value = cevent.allDay;
key = (int)cmd.ExecuteScalar();
}
return key;
}
}
another class used in between javascript and asp.net
ImproperCalendarEvent.cs
public class ImproperCalendarEvent
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
public bool allDay { get; set; }
}
the javascript file code -calendarscript.js
var currentUpdateEvent;
var addStartDate;
var addEndDate;
var globalAllDay;
function updateEvent(event, element) {
alert(event.description);
if ($(this).data("qtip")) $(this).qtip("destroy");
currentUpdateEvent = event;
$('#updatedialog').dialog('open');
$("#eventName").val(event.title);
$("#eventDesc").val(event.description);
$("#eventId").val(event.id);
$("#eventStart").text("" + event.start.toLocaleString());
if (event.end === null) {
$("#eventEnd").text("");
}
else {
$("#eventEnd").text("" + event.end.toLocaleString());
}
return false;
}
function updateSuccess(updateResult) {
alert(updateResult);
}
function deleteSuccess(deleteResult) {
alert(deleteResult);
}
function addSuccess(addResult) {
// if addresult is -1, means event was not added
// alert("added key: " + addResult);
if (addResult != -1) {
$('#calendar').fullCalendar('renderEvent',
{
title: $("#addEventName").val(),
start: addStartDate,
end: addEndDate,
id: addResult,
description: $("#addEventDesc").val(),
allDay: globalAllDay
},
true // make the event "stick"
);
$('#calendar').fullCalendar('unselect');
}
}
function UpdateTimeSuccess(updateResult) {
alert(updateResult);
}
function selectDate(start, end, allDay) {
$('#addDialog').dialog('open');
$("#addEventStartDate").text("" + start.toLocaleString());
$("#addEventEndDate").text("" + end.toLocaleString());
addStartDate = start;
addEndDate = end;
globalAllDay = allDay;
//alert(allDay);
}
function updateEventOnDropResize(event, allDay) {
//alert("allday: " + allDay);
var eventToUpdate = {
id: event.id,
start: event.start
};
if (event.end === null) {
eventToUpdate.end = eventToUpdate.start;
}
else {
eventToUpdate.end = event.end;
}
var endDate;
if (!event.allDay) {
endDate = new Date(eventToUpdate.end + 60 * 60000);
endDate = endDate.toJSON();
}
else {
endDate = eventToUpdate.end.toJSON();
}
eventToUpdate.start = eventToUpdate.start.toJSON();
eventToUpdate.end = eventToUpdate.end.toJSON(); //endDate;
eventToUpdate.allDay = event.allDay;
PageMethods.UpdateEventTime(eventToUpdate, UpdateTimeSuccess);
}
function eventDropped(event, dayDelta, minuteDelta, allDay, revertFunc) {
if ($(this).data("qtip")) $(this).qtip("destroy");
updateEventOnDropResize(event);
}
function eventResized(event, dayDelta, minuteDelta, revertFunc) {
if ($(this).data("qtip")) $(this).qtip("destroy");
updateEventOnDropResize(event);
}
function checkForSpecialChars(stringToCheck) {
//var pattern = /[^A-Za-z0-9 ]/;
//return pattern.test(stringToCheck);
return true;
}
function isAllDay(startDate, endDate) {
var allDay;
if (startDate.format("HH:mm:ss") == "00:00:00" && endDate.format("HH:mm:ss") == "00:00:00") {
allDay = true;
globalAllDay = true;
}
else {
allDay = false;
globalAllDay = false;
}
return allDay;
}
function qTipText(start, end, description) {
var text;
if (end !== null)
text = "<strong>Start:</strong> " + start.format("MM/DD/YYYY hh:mm T") + "<br/><strong>End:</strong> " + end.format("MM/DD/YYYY hh:mm T") + "<br/><br/>" + description;
else
text = "<strong>Start:</strong> " + start.format("MM/DD/YYYY hh:mm T") + "<br/><strong>End:</strong><br/><br/>" + description;
return text;
}
$(document).ready(function () {
// update Dialog
$('#updatedialog').dialog({
autoOpen: false,
width: 470,
buttons: {
"update": function () {
alert(currentUpdateEvent.title);
var eventToUpdate = {
id: currentUpdateEvent.id,
name: $("#eventName").val(),
description: $("#eventDesc").val()
};
PageMethods.UpdateEvent(eventToUpdate, updateSuccess);
$(this).dialog("close");
currentUpdateEvent.title = $("#eventName").val();
currentUpdateEvent.description = $("#eventDesc").val();
$('#calendar').fullCalendar('updateEvent', currentUpdateEvent);
},
"delete": function () {
if (confirm("do you really want to delete this event?")) {
PageMethods.deleteEvent($("#eventId").val(), deleteSuccess);
$(this).dialog("close");
$('#calendar').fullCalendar('removeEvents', $("#eventId").val());
}
}
}
});
//add dialog
$('#addDialog').dialog({
autoOpen: false,
width: 470,
buttons: {
"Add": function () {
//alert("sent:" + addStartDate.format("dd-MM-yyyy hh:mm:ss tt") + "==" + addStartDate.toLocaleString());
var eventToAdd = {
title: $("#addEventName").val(),
description: $("#addEventDesc").val(),
start: addStartDate.toJSON(),
end: addEndDate.toJSON(),
allDay: isAllDay(addStartDate, addEndDate)
};
if (checkForSpecialChars(eventToAdd.title) || checkForSpecialChars(eventToAdd.description)) {
alert("please enter characters: A to Z, a to z, 0 to 9, spaces");
}
else {
//alert("sending " + eventToAdd.title);
PageMethods.addEvent(eventToAdd, addSuccess);
$(this).dialog("close");
}
}
}
});
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var options = {
weekday: "long", year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today customBtn',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
customButtons: {
customBtn: {
text: 'Custom Button',
click: function () {
alert('This custom button is hot! 🔥\nNow go have fun!');
}
}
},
defaultView: 'agendaWeek',
eventClick: updateEvent,
selectable: true,
selectHelper: true,
select: selectDate,
editable: true,
events: "JsonResponse.ashx",
eventDrop: eventDropped,
eventResize: eventResized,
eventRender: function (event, element) {
//alert(event.title);
element.qtip({
content: {
text: qTipText(event.start, event.end, event.description),
title: '<strong>' + event.title + '</strong>'
},
position: {
my: 'bottom left',
at: 'top right'
},
style: { classes: 'qtip-shadow qtip-rounded' }
});
}
});
});

Related

Ajax & ASP.NET Core MVC 6..0 : Get data by ID without using Entity Framework

I am trying to get data in my DataTable by ID, the data row coming from SQL Server to my controller and passing to Jquery-Ajax but After processing in Ajax, I am getting only UNDEFINED in my DataTable View?
Please note: I have used below code successfully in my ASP.Net MVC app but now after upgrading to ASP.NET CORE MVC 6.0, It is giving only UNDEFINED.
my model:
public class EmployeesModel
{
public int EmployeeId { get; set; }
public string? Name { get; set; }
public string? Gender { get; set; }
public int Age { get; set; }
public string? Position { get; set; }
public string? Office { get; set; }
[Required(ErrorMessage = "Please enter date")]
public DateTime HiringDate { get; set; }
public int Salary { get; set; }
}
My controller
[HttpGet]
public JsonResult GetEmpByName(string Name)
{
List<EmployeesModel> employeeList = new List<EmployeesModel>();
string CS = this.Configuration.GetConnectionString("SQLConn");
using (SqlConnection conn = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_GetEmpByName", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpName", SqlDbType.NVarChar).Value = Name; //Added Parameter
conn.Open();
// Get
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EmployeesModel employee = new EmployeesModel();
employee.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);
employee.Name = reader["Name"].ToString();
employee.Gender = reader["Gender"].ToString();
employee.Age = Convert.ToInt32(reader["Age"]);
employee.Position = reader["Position"].ToString();
employee.Office = reader["Office"].ToString();
employee.HiringDate = Convert.ToDateTime(reader["HiringDate"]);
employee.Salary = Convert.ToInt32(reader["Salary"]);
employeeList.Add(employee);
}
}
return Json(new { data = employeeList.ToList(), success = true, responsetext = "Added" });
}
My view
#model IEnumerable<SQLWithoutEF.EmployeesModel>
<div class="form-control">
<select class="form-select" id="drpList" onchange="getSelectedValue()">
<option selected disabled>Please Select</option>
#foreach(var employee in ViewBag.Employees)
{
<option value="#employee.EmployeeId">#employee.Name</option>
}
</select>
</div>
//Here I enter Employee Name and below is button
<Button runat="server" Text="Button" class="btn btn-danger" id="IDbtn" onclick="GetByName($('#drpList').val())">Get Data By Name</Button>
#*Data Table ==============*#
<table class="table table-bordered table-responsive table-hover" id="MyTable">
<thead>
<tr>
<th style="display:none">#Html.DisplayNameFor(m => m.EmployeeId)</th>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.Gender)</th>
<th>#Html.DisplayNameFor(m => m.Age)</th>
<th>#Html.DisplayNameFor(m => m.Position)</th>
<th>#Html.DisplayNameFor(m => m.Office)</th>
<th>#Html.DisplayNameFor(m => m.HiringDate)</th>
<th>#Html.DisplayNameFor(m => m.Salary)</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var employee1 in Model)
{
<tr>
<td style="display:none">#employee1.EmployeeId</td>
<td>#employee1.Name</td>
<td>#employee1.Gender</td>
<td>#employee1.Age</td>
<td>#employee1.Position</td>
<td>#employee1.Office</td>
<td>#employee1.HiringDate</td>
<td>#employee1.Salary</td>
<td>
<asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> |
<asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button>
</td>
</tr>
}
</tbody>
</table>
My jQuery / Ajax - here I need help: I have tried 3 methods but all fail
function GetByName(Name) {
$('#MyTable tbody tr').remove();
$.ajax({
type: "GET",
url: '/Home/GetEmpByName?Name=' + Name,
//data: JSON.stringify({ id: id }), commented out
//contentType: application/json, charset: utf - 8, commented out
//cache: false, commented out
processData: false,
dataType: 'json',
bprocessing: true,
success: function (data) {
var items = [data.data[0]]; //This line may be wrong, I am not sure.
debugger;
3rd try -Failed
//let rows = data.map(i=> "<tr><td>" + i.Name + "</td></tr>");
2nd try -failed
// for (var i = 1; i < items.length-1; i++) {
// var rows = $('<tr> <td style="Display:none">' + items[EmployeeID] + '</td><td>' + items.data[i].Name + '</td><td>' + items[i][2] + '</td><td>' + items[i][3] + '</td><td>' + items[i][4] + '</td><td>' + items[i][5] + '</td><td>' + items[i][6] + '</td><td>' + items[i][7] + '</td><td>' + items[i][8] + '</td></tr>');
// $('#MyTable tbody').append(rows);
// };
// 1st try failed
$.each(items, function (index, item) {
var rows = '';
rows = `<tr>
<td style="Display:none">${item.EmployeeId}</td>
<td>${item.Name}</td>
<td>${item.Gender}</td>
<td>${item.Age}</td>
<td>${item.Position}</td>
<td>${item.Office}</td>
<td>${2020-04-04}</td>
<td>${item.Salary}</td>
<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="${item.Name}" id="deletebtn" onclick="deleteF(${item.EmployeeId})">DeleteEmp</asp:button></td>
</tr>`
$('#MyTable tbody').append(rows);
});
},
complete: function () {
// setTimeout(function () {
// $('.ajaxLoader').hide();
// }, 300);
}
}).catch(function (xhr, status, error) {
var errorMeassage = xhr.status + ': ' + xhr.statusText;
alert('Error - ' + errorMeassage);
})
};
};
Here is the screenshot what output I am getting
How can I send data from my controller to my DataTable using Ajax?
It's because you return your data with employeeId, name properties but you try to append with EmployeeId, Name. You need to be careful with casing of your object.
rows = `<tr>
<td style="Display:none">${item.employeeId}</td>
<td>${item.name}</td>
<td>${item.gender}</td> ...

How do you move data from one cell in one row of a web grid to another cell in another row that is empty using jQuery?

I am kind of lost when it comes to jQuery sometimes, though I know there is a way! How do you update or move three cells data to another row based on the rows id to where the row is green (empty cells)? The row column ID name is "LocationID". MVC application using a web grid. What I am trying to do is when I check the row, use the drop-down that has the id, send the data to that row where the id exists populating the three empty cells in green with the current columnar data row that is checked. Any help would be greatly appreciated!
WebGrid below:
enter
<div id="content">
#webGrid.GetHtml(tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
//alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
htmlAttributes: new { #id = "webGrid" },
columns: webGrid.Columns(
webGrid.Column(header: "Actions", format:#<span class="link">
<!--Add Checkbox here-->
<!-- Note: We can add clickable rows as an option for user using a checkbox, one
selects the data move and the other move to selection. -->
#Html.CheckBoxFor(model => model.SelectedMoveIsChecked, new { #Class =
"SelectedMoveIsChecked", #id = "SelectedMoveIsChecked", #checked = false })
#Html.CheckBoxFor(model => model.SelectedMoveToChecked, new { #Class =
"SelectedMoveToChecked", #id = "SelectedMoveToChecked", #checked = false })
<!-- Html.CheckBox("isActive", false, item.isSelectdRow, true, new { id =
"CheckBoxSelectedBeginMove", Class = "CheckBoxIsSelected" })
Html.CheckBoxFor(Model.Input_Location, item.isSelectdRow, new { = "'SelectedRows'",
data_val = item.Location })
-->
<a class="Edit" href="javascript:;">Edit</a>
<a class="Clear" href="javascript:;">Clear</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</span>),
webGrid.Column(header: "Location", format: #<div>
<label id="LocationLbl" class="label">#item.Location</label>
<input id="Location" class="text" type="text" value="#item.Location" style="display:none"
/><br />
#Html.DropDownListFor(model => model.LocationAppended, Model.LocationAppended,
"Section/Location", new { IReadOnlyDictionary = "document.forms[0].submit();", #id =
"RowLocationDropDownList", #class = "RowLocationDropDownList", #visibility = "hidden",
#placeholder = "Location" })
</div>, style: "Location"),
webGrid.Column(header: "Section", format: #<div>
<label id="SectionLbl" class="label">#item.Section</label>
<input id="Section" class="text" type="text" value="#item.Section" style="display:none" />
</div>, style: "Section"),
webGrid.Column(header: "TrailerNumber", format: #<div>
<label id="TrailerNumberLbl" class="label">#item.TrailerNumber</label>
<input id="TrailerNumber" class="text" type="text" value="#item.TrailerNumber"
style="display:none" />
</div>, style: "TrailerNumber"),
webGrid.Column(header: "CarrierName", format: #<div>
<label id="CarrierNameLbl" class="label">#item.CarrierName</label>
<input id="CarrierName" class="text" type="text" value="#item.CarrierName"
style="display:none" />
</div>, style: "CarrierName"),
webGrid.Column(header: "LoadCommodityStatus", format: #<div>
<label id="LoadCommodityStatusLbl" class="label">#item.LoadCommodityStatus</label>
<input id="LoadCommodityStatus" class="text" type="text" value="#item.LoadCommodityStatus"
style="display:none" />
</div>, style: "LoadCommodityStatus"),
webGrid.Column(header: "DateLoaded", format: #<div>
<label id="DateLoadedLbl" class="label">#item.DateLoaded</label>
<input id="DateLoaded" class="text" type="text" value="#item.DateLoaded" style="display:none"
/>
</div>, style: "DateLoaded"),
webGrid.Column(header: "UserName", format: #<div>
<label id="UserNameLbl" class="label">#item.UserName</label>
<input id="UserName" class="text" type="text" value="#item.UserName" style="display:none" />
</div>, style: "UserName"),
webGrid.Column(header: "PlantLocation", format: #<div>
<label id="PlantLocationLbl" class="label">#item.PlantLocation</label>
<input id="PlantLocation" class="text" type="text" value="#item.PlantLocation"
style="display:none" />
</div>, style: "PlantLocation"),
webGrid.Column(header: "RowPageID", format: #<div>
<label id="LocationIDLbl" class="label">#item.LocationID</label>
</div>, style: "LocationID"))),
<div id="RowCountBpttom"><b>Records: #firstRecord - #lastRecord of
#webGrid.TotalRowCount</b></div>
</div>
<br />
<div class="WebGridTable">
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">
</script>
<script src="~/Scripts/YardDogAdmin.js"></script>
</body>
jQuery Below:
code here
enter
$('select.RowLocationDropDownList').attr('disabled', true);
$(".SelectedMoveIsChecked").change(function (i, row) {
$actualRowColorRed = $(row);
//When a value is selected in the dropdownlist box.
if ($(this).children("option:selected").val() != '') {
$("select.RowLocationDropDownList").change(function (i, row) {
$actualRowColorRed = $(row);
//Checks to see if the checkbox is checked, display the alert showing data and color the row red again.
/////// if ($('.SelectedMoveIsChecked').is(':checked') == true) {
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[0];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[1];
var RowLocation = ret[2];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
// var ConfirmStr = " <b>Are you sure, you want to move this row From: </b>" + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
// alert("Alert " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?"
// );
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
//Add new values to (TrailerNumber, CarrierName, LoadCommodityStatus, DateLoaded, UserName).
//Note: Get the UserName currently using the Yard Dog Application.
/// $('#webGrid').closest('tr').find('#TrailerNumber').val();
/// $("#webGrid tbody tr").each(function (i, row) {
// $('#webGrid tbody tr').find('#LocationID'.val(RowLocationIDNum); //= RowLocationIDNum).append('#TrailerNumber'.val(CurrentRowTrailerNumber));
$("body").on("change", "select.RowLocationDropDownList", function () {
// $("body").on("click", "#webGrid TBODY .Update", function () {
// $("#content").on("click", "#webGrid INPUT", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
span.html(input.val());
}
});
//// $('#webGrid tbody tr').find('#LocationID').val(RowLocationIDNum) = customer;
var RowExchange = $(RowLocationID).closest("tr");
var ToRow = {};
ToRow.LocationID = row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
/*
ToRow.LocationID = RowExchange.find('#LocationID').append(RowLocationID) ;
ToRow.UserName = RowExchange.find('.UserName').append(row.find(".UserName").find(".label").html());
ToRow.Location = RowExchange.find('.Location').append(row.find(".Location").find(".label").html());
ToRow.Section = RowExchange.find('.Section').append(row.find(".Section").find(".label").html());
ToRow.TrailerNumber = RowExchange.find('.TrailerNumber').append(ToRow.TrailerNumber);
ToRow.CarrierName = RowExchange.find('.CarrierName').val().append(ToRow.CarrierName);
ToRow.LoadCommodityStatus = RowExchange.find('.LoadCommodityStatus').append(ToRow.LoadCommodityStatus);
ToRow.DateLoaded = RowExchange.find('.DateLoaded').append(row.find(".DateLoaded").find(".label").html());
ToRow.PlantLocation = RowExchange.find('.PlantLocation').append(row.find(".PlantLocation").find(".label").html());
*/
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) +'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 777);
});
}
else {
confirm_value.value = "Cancel";
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
code here
Controller:
enter [HttpPost]
public ActionResult UpdateRowExchange(LocationData ToRow)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == ToRow.LocationID
select c).FirstOrDefault();
//Check for Duplicates.
///FindDuplicates(customer);
//HighlightDuplicate(webGrid);
//x => customer.TrailerNumber == x.TrailerNumber && x.TrailerNumber == customer.TrailerNumber //errases all data except the first cell TrailerNumber.
if (ToRow.UserName != null) updatedCustomer.UserName = ToRow.UserName.ToUpper();
else updatedCustomer.UserName = ToRow.UserName = null;
/*
if (customer.Location != null) updatedCustomer.Location = customer.Location.ToUpper();
else updatedCustomer.Location = customer.Location = null;
if (customer.Section != null) updatedCustomer.Section = customer.Section.ToUpper();
else updatedCustomer.Section = customer.Section = null;
*/
if (ToRow.TrailerNumber != null) updatedCustomer.TrailerNumber = ToRow.TrailerNumber.ToUpper();
else updatedCustomer.TrailerNumber = ToRow.TrailerNumber = null;
if (ToRow.CarrierName != null) updatedCustomer.CarrierName = ToRow.CarrierName.ToUpper();
else updatedCustomer.CarrierName = ToRow.CarrierName = null;
if (ToRow.LoadCommodityStatus != null) updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus.ToUpper();
else updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus = null;
if (ToRow.DateLoaded != null) updatedCustomer.DateLoaded = ToRow.DateLoaded.ToUpper();
else updatedCustomer.DateLoaded = ToRow.DateLoaded = null;
/*
if (customer.PlantLocation != null) updatedCustomer.PlantLocation = customer.PlantLocation.ToUpper();
else updatedCustomer.PlantLocation = customer.PlantLocation = null;
*/
//Create today's Date for a timestamp of inputs.
DateTime now = DateTime.Today;
ToRow.DateLoaded = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
updatedCustomer.DateLoaded = ToRow.DateLoaded;
entities.SaveChanges();
//Refresh(out, customer.ToString());
}
return new EmptyResult();
}
code here
Model below:
enter code here
namespace YardDog.Model
{
public class YardDogModel
{
ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
//Two Properties for DropDownList.
public List<LocationData> LocationDatas { get; set; }
//public List<LocationData> Location { get; set; }
public List<LocationData> TrailerNumber { get; set; }
public List<SelectListItem> PlantLocation { get; set; }
public List<SelectListItem> Location { get; set; }
public List<SelectListItem> LocationList { get; set; }
public List<SelectListItem> SectionList { get; set; }
public List<SelectListItem> LocationAppended { get; set; }
[Display(Name = "Name")]
public List<SelectListItem> Section { get; set; }
public List<SelectListItem> ListDuplicates { get; set; }
public List<SelectListItem> UserName { get; set; }
//Allow the data to be transfered (Backend into SQL Server).
[Required]
public string Input_Location { get; set; }
[Required]
public string Input_Section { get; set; }
public string Input_TrailerNumber { get; set; }
public string Input_CarrierName { get; set; }
public string Input_CommodityLoadStatus { get; set; }
[Required]
public string Input_PlantLocation { get; set; }
//YardDogModel YardDogDatas = new YardDogModel();
//string TrailerNumber = Input_TrailerNumber;
public bool SelectedMoveIsChecked { get; set; } = false;
public bool SelectedMoveToChecked { get; set; } = false;
public string LocationAppendedLbl { get; internal set; }
//public string LocationAppended { get; internal set; }
public string RowLocationDropDownList { get; set; }
public int RowLocationIDNum { get; set; }
}
}
JavaScript:
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[2];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[0];
var RowLocation = ret[1];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
$("body").on("change", "select.RowLocationDropDownList", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
span.html(input.val());
}
});
//Tell the row change to be where ID exists by ID Number (RowLocationIDNum).
var ToRow = {};
ToRow.LocationID = RowLocationIDNum; //row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
});
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 500);
});
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 500);
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
});
}
});

Dropdownlist not working

Why is the property DEPARTMENTID not inserting into the database on create, I am using Dropdownlist
see the code below, this all my code i need your idea to correct my code.
Controller
// GET: /Budget/Create
public ActionResult Create()
{
var name = User.Identity.GetUserName();
var userroles = _roleDataContext.USERROLEs.Where(u => u.USERNAME.ToLower().Trim() == name.ToLower().Trim() && u.ROLE.Trim() == "6");
var rolegroup = from u in userroles.ToList()
join rg in _roleDataContext.ROLEGROUPs.ToList()
on u.ROLEID equals rg.ROLEID
select rg;
var usergroup = (from rg in rolegroup.ToList()
join ug in _roleDataContext.USERGROUPs.ToList()
on rg.GROUPID equals ug.GROUPID
select ug).OrderBy(i => i.DEPTCODE);
var listSelectitem = usergroup.Select(#group => new SelectListItem
{
Selected = true,
Text = #group.DEPTCODE.Length > 20 ? #group.DEPTCODE.Substring(0, 20) : #group.DEPTCODE,
Value = #group.DEPTCODE
}).ToList();
var firstOrDefault = usergroup.FirstOrDefault();
if (firstOrDefault != null)
{
ViewBag.DeptList = new SelectList(listSelectitem, "Value", "Text", firstOrDefault.DEPTCODE);
}
return View();
}
// POST: /Budget/Create
[HttpPost]
public ActionResult Create(BudgetViewModel model , int month = 1, int year = 2017)
{
// TODO: Add insert logic here
model.DATETIME = DateTime.Now;
BudgetDb.insert(model);
return RedirectToAction("Index");
}
View
#model WarehouseRtoRSystem.Models.BudgetViewModel
#{
ViewBag.Title = "Create";
}
<style>
.col-md-10 {
clear: both;
padding-left: 0px !important;
}
.col-md-2 {
text-align: left !important;
}
</style>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Budget</h2>
<hr />
#Html.ValidationSummary(true)
<label>Month </label>
<select id="month" name="month">
#{ string[] Months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; }
#for (var i = 0; i < 12; i++)
{
var m = i + 1;
if (Convert.ToInt32(ViewBag.month) == m)
{
<option value=#m selected>#Months[i]</option>
}
else
{
<option value=#m>#Months[i]</option>
}
}
</select>
<label>YEAR</label>
<select id="year" name="year">
#for (var c = 0; c < 1000; c++)
{
var yr = c + 2017;
if (Convert.ToInt32(ViewBag.year) == yr)
{
<option value=#yr selected>
#yr
</option>
}
else
{
<option value=#yr> #yr</option>
}
}
</select>
<br />
<br />
<div class="form-group">
<label> LIST OF YOUR DEPARTMENT</label>
<span class="">#Html.DropDownList("DEPARTMENTID", (SelectList)ViewBag.DeptList, new { #class = "form-control" })</span>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BUDGET, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("ShowBudget", null, new { #class = "form-control" })
#Html.HiddenFor(model => model.BUDGET, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BUDGET)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
<br />
<br />
<br />
</div>
}
<div>
#Html.ActionLink("Back to List", "Index", null, new { #class ="btn btn-primary"})
</div>
<script>
$(document).ready(function () {
$("#ShowBudget").change(function () {
var value = parseFloat($(this).val());
$("#BUDGET").val(value); //assign the current value to BUDGET field
if (!isNaN(value)) {
var result = value.toLocaleString(
"en-US", // use a string like 'en-US' to override browser locale
{ minimumFractionDigits: 2 }
);
$(this).val(result);
}
})
})
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Model
namespace WarehouseRtoRSystem.Models
{
public class BudgetModel
{
public int MONTH { get; set; }
public int YEAR { get; set; }
public string DEPARTMENTID { get; set; }
public DateTime DATETIME { get; set; }
//[DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
public double BUDGET { get; set; }
public string GROUPID { get; set; }
}
public class BudgetViewModel : BudgetModel
{
public string DEPARTMENTNAME { get; set; }
public double EXPENCES { get; set; }
public double BALANCE { get; set; }
}
public class BudgetContext
{
private readonly OracleCommand cmd = new OracleCommand();
private OracleConnection Conn = new OracleConnection();
private readonly OracleConnModel ORCONN = new OracleConnModel();
public List<BudgetViewModel> List()
{
var Departments = new List<BudgetViewModel>();
///SQL QUERY
Conn = ORCONN.con;
if (Conn.State != ConnectionState.Open)
{
Conn.Open();
}
try
{
cmd.Connection = Conn;
cmd.CommandText = "SELECT * From PH.SYSTEMBUDGET";
cmd.CommandType = CommandType.Text;
var dr = cmd.ExecuteReader();
while (dr.Read())
{
var Dept = new BudgetViewModel();
Dept.MONTH = dr.GetInt32(0);
Dept.YEAR = dr.GetInt32(1);
Dept.DEPARTMENTID = dr.GetString(2);
Dept.DATETIME = dr.GetDateTime(3);
Dept.BUDGET = dr.GetDouble(4);
Dept.GROUPID = dr.IsDBNull(5) ? "" : dr.GetString(5);
Departments.Add(Dept);
}
}
finally
{
Conn.Close();
}
return Departments;
}
public string insert(BudgetModel model)
{
Conn = ORCONN.con;
if (Conn.State != ConnectionState.Open)
{
Conn.Open();
}
try
{
cmd.Connection = Conn;
//var date = new DateTime();
// date = DateTime.Now;
var query = "INSERT into PH.SYSTEMBUDGET(";
query += "MONTH,";
query += "YEAR,";
query += "DEPARTMENTID,";
query += "DATETIME,";
query += "BUDGET,";
query += "GROUPID";
query += ")";
query += "VALUES(";
query += "'" + model.MONTH + "',";
query += "'" + model.YEAR + "',";
query += "'" + model.DEPARTMENTID + "',";
query += "TO_DATE('" + DateTime.Now + "','MM/DD/YYYY HH:MI:SS AM'),";
query += "'"+ model.BUDGET + "'," ;
query += "'" + model.GROUPID + "'";
query += ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
finally
{
Conn.Close();
}
return "Seccessfully inserted";
}
}
}
The error resides in the following code in your controller, whereby you are setting the Value of the SelectListItem to be the DEPTCODE description instead of the ID of the DEPTCODE record
Here is your code:
var listSelectitem = usergroup.Select(#group => new SelectListItem
{
Selected = true,
Text = #group.DEPTCODE.Length > 20 ? #group.DEPTCODE.Substring(0, 20) : #group.DEPTCODE,
Value = #group.DEPTCODE
}).ToList();
The issue is here:
Value = #group.DEPTCODE
Now apologies for not re-creating the code exactly in the controller but the DEPTCODE models were not available, so I improvised slightly.
Here is my Create Controller:
[HttpGet]
public ActionResult Create()
{
List<DeptCode> _depts = new List<DeptCode>();
_depts.Add(new DeptCode { Id = 0, Description = "IT"});
_depts.Add(new DeptCode { Id = 1, Description = "Customer Services" });
_depts.Add(new DeptCode { Id = 2, Description = "Warehouse" });
var _listSelectItem = _depts.Select(#group => new SelectListItem
{
Selected = true,
Text = #group.Description,
Value = #group.Id.ToString()
}).ToList();
var firstOrDefault = _listSelectItem.FirstOrDefault();
if(firstOrDefault != null)
{
ViewBag.DeptList = new SelectList(_listSelectItem, "Value", "Text", firstOrDefault.Text);
}
return View();
}
I have created my SelectListItem with the Value of the Id of the record, because in your code, you were binding ViewBag.DeptList with a SelectList whereby the dataValueField (Source) property was "Value".:
ViewBag.DeptList = new SelectList(_listSelectItem, "Value", "Text", firstOrDefault.Text);
So in my example I have selected a Warehouse department (again I made this value up for the sake of my model), and pressed Create.:
As you can see, this is now bound to model.DEPARTMENTID:
I have added my code here if you want to see how it works:
https://github.com/garfbradaz/StackOverFlowAnswers/tree/master/ASP.NET%20MVC/DropDownListNotWorking/SOAnswer-44879268

How to bind data to grid column using array

aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/HomeMaster.master" AutoEventWireup="true" CodeFile="V_MaterCode.aspx.cs" Inherits="V_MaterCode" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "V_MaterCode.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grd_mastercodes").append("<tr><td>" + data.d[i].Vendor + "</td><td>" + data.d[i].SearchTerm + "</td><td>" + data.d[i].Vendor_Name + "</td><td>" + data.d[i].Street + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td><td>" + data.d[i].PO_Box + "</td><td>" + data.d[i].Currency + "</td><td>" + data.d[i].Sales_Person + "</td><td>" + data.d[i].Telephone_Number + "</td><td>" + data.d[i].Ext_01 + "</td><td>" + data.d[i].Ext_02 + "</td><td>" + data.d[i].Minimum_Value + "</td><td>" + data.d[i].Post_Code + "</td><td>" + data.d[i].Group + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" LoadScriptsBeforeUI="false"
EnablePartialRendering="false">
</asp:ScriptManager>
<div class="contentarea">
<br />
<asp:Label ID="lblsub" Style="overflow-x: auto; margin-left: 20px;" runat="server" Text="Station master data entry" />
</div>
<div style="margin: 0 auto; overflow: auto; padding: 10px 20px;">
<asp:GridView ID="grd_mastercodes" runat="server" HeaderStyle-BackColor="#f79646" HeaderStyle-ForeColor="White"
HeaderStyle-Font-Bold="false" Font-Names="Calibri"
Font-Size="Medium" RowStyle-BackColor="White" HeaderStyle-BorderColor="Black"
AutoGenerateColumns="False" RowStyle-BorderColor="Black" OnRowCreated="grd_mastercodes_RowCreated">
</asp:GridView>
</div>
</asp:Content>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using AjaxControlToolkit;
public partial class V_MaterCode : System.Web.UI.Page
{
string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
bool rowset = false;
GridView dgv = new GridView();
// For First gridview
String[] gridColumnNames_mastercodes = { "Vendor Code", "Search Term", "Vendor Name", "Street", "City", "Country", "Post Box", "Currency", "Sales Person", "Telephone Number", "Ext_01", "Ext_02", "Minimum Value", "Post Code", "Group" };
String[] gridColumnwidth_mastercodes = { "50px", "200px", "200px", "150px", "100px", "100px", "100px", "100px", "150px", "150px", "150px", "150px", "100px", "100px", "100px" };
int[] gridColumnWidth_mastercodes = { 3, 15, 15, 13, 10, 10, 10, 10, 13, 13, 13, 13, 10, 10, 10 };
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
//For First gridview
DataTable dt = new DataTable();
for (int c = 0; c < gridColumnNames_mastercodes.Length; c++)
{
DataColumn dcol = new DataColumn(c.ToString(), typeof(System.Int32));
dcol.ColumnName = gridColumnNames_mastercodes[c];
dt.Columns.Add(dcol);
TemplateField tf = new TemplateField();
tf.HeaderStyle.Font.Bold = false;
tf.HeaderText = gridColumnNames_mastercodes[c];
tf.HeaderStyle.Width = new Unit(gridColumnwidth_mastercodes[c]);
grd_mastercodes.Columns.Add(tf);
}
for (int i = 0; i < 15; i++)
{
dt.Rows.Add(dt.NewRow());
}
grd_mastercodes.DataSource = dt;
grd_mastercodes.DataBind();
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}
BindColumnToGridview();
}
private void BindColumnToGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("Vendor");
dt.Columns.Add("Search Term");
dt.Columns.Add("Vendor Name");
dt.Columns.Add("Street");
dt.Columns.Add("City");
dt.Columns.Add("Country");
dt.Columns.Add("Post Box");
dt.Columns.Add("Currency");
dt.Columns.Add("Sales Person");
dt.Columns.Add("Telephone Number");
dt.Columns.Add("Ext_01");
dt.Columns.Add("Ext_02");
dt.Columns.Add("Minimum Value");
dt.Columns.Add("Post Code");
dt.Columns.Add("Group");
dt.Rows.Add();
grd_mastercodes.DataSource = dt;
grd_mastercodes.DataBind();
//grd_mastercodes.Rows[0].Visible = false;
}
[WebMethod]
public static UserDetails[] BindDatatable()
{
string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
DataTable dt = new DataTable();
List<UserDetails> details = new List<UserDetails>();
using (SqlConnection con = new SqlConnection(connectionstring))
{
using (SqlCommand cmd = new SqlCommand("Select * From ArR_VendorMaster", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.Vendor = dtrow["Vendor"].ToString();
user.SearchTerm = dtrow["SearchTerm"].ToString();
user.Vendor_Name = dtrow["Vendor_Name"].ToString();
user.Street = dtrow["Street"].ToString();
user.City = dtrow["City"].ToString();
user.Country = dtrow["Country"].ToString();
user.PO_Box = dtrow["PO_Box"].ToString();
user.Currency = dtrow["Currency"].ToString();
user.Sales_Person = dtrow["Sales_Person"].ToString();
user.Telephone_Number = dtrow["Telephone_Number"].ToString();
user.Ext_01 = dtrow["Ext_01"].ToString();
user.Ext_02 = dtrow["Ext_02"].ToString();
user.Minimum_Value = dtrow["Minimum_Value"].ToString();
user.Post_Code = dtrow["Post_Code"].ToString();
user.Group = dtrow["Group"].ToString();
details.Add(user);
}
}
}
return details.ToArray();
}
public class UserDetails
{
public string Vendor { get; set; }
public string SearchTerm { get; set; }
public string Vendor_Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PO_Box { get; set; }
public string Currency { get; set; }
public string Sales_Person { get; set; }
public string Telephone_Number { get; set; }
public string Ext_01 { get; set; }
public string Ext_02 { get; set; }
public string Minimum_Value { get; set; }
public string Post_Code { get; set; }
public string Group { get; set; }
}
//For First Gridview
protected void grd_mastercodes_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int rc = 0; rc < grd_mastercodes.Columns.Count; rc++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "Excel_mastercodes" + e.Row.RowIndex + "_" + rc;
txtBox.MaxLength = gridColumnWidth_mastercodes[rc];
txtBox.Width = new Unit(gridColumnwidth_mastercodes[rc]);
txtBox.BorderStyle = BorderStyle.None;
e.Row.Cells[rc].Controls.Add(txtBox);
e.Row.Cells[rc].Attributes.Add("onKeyDown", "enter(this);");
if (rc == 3)
txtBox.Style["text-align"] = "left";
else
txtBox.Style["text-align"] = "center";
}
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}
}
}
I need to bind data but it displaying column name only . It's not binding any data . weather i am doing in a correct . If any body knows how to get data please suggest me. I am using array and i am not sure how to bind data in array . I need your help

how do I return multi dimension lists to view from controller?

I am trying to return a multi dimension list from controller to view.
I have a
Model
ViewModel
View
Controller
ViewModel:
public class HomeViewModel
{
public DateTime Date { get; set; }
public List<Snapshot> SnapshotItems { get; set; }
}
View:
#model IEnumerable<myproject.ViewModels.HomeViewModel>
<div class="pi-section pi-padding-top-20 pi-padding-bottom-10">
#foreach (var items in Model)
{
<div class="pi-container">
<div class="pi-col-lg-12">
#items.Date.ToString("MMM, dd, 2014")
</div>
</div>
<div class="pi-container">
#foreach (var item in items.SnapshotItems)
{
<div class="item pi-col-lg-4">
<div class="">#Html.ActionLink(item.BrandName, "Index", "Brand", new { guid = item.BrandGuid, brandName = FriendlyUrl.Convert((item.BrandName).ToString()) }, null)</div>
<div class="snapshot-photo-home">
<a class="image_rollover_bottom con_borderImage" data-description="ZOOM IN" href="#Url.Action("html", "snapshot" , new { guid = item.Guid })" target="_blank">
<img class="lazyload" src="#item.Thumbnail" width="300" />
</a>
</div>
<span class="home-subject">#item.Subject</span>
<div class="snapshot-action">
</div>
</div>
}
</div>
}
</div>
Controller:
public PartialViewResult RecentEmails()
{
int days = 2;
HomeViewModel viewModel = new HomeViewModel();
List<Snapshot> snapshots = new List<Snapshot>();
List<HomeViewModel> viewModelList = new List<HomeViewModel>();
for (int count = 0; count < days; count++)
{
viewModel.Date = DateTime.Now.AddDays(count * (-1));
snapshots = GetEmailSnapshot(9, viewModel.Date);
viewModel.SnapshotItems = snapshots;
}
viewModelList.Add(viewModel);
return PartialView(viewModelList.AsEnumerable());
}
private List<Snapshot> GetEmailSnapshot(int numSnapshots, DateTime dateReceived)
{
List<Snapshot> snapshots = new List<Snapshot>();
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
string date = dateReceived.ToString("yyyy/MM/dd");
dbCmd.CommandText = "SELECT a.snapshot_id, a.subject, a.snapshot_guid, a.date_sent, a.image, a.thumbnail, a.status, b.name, b.brand_guid FROM snapshots a INNER JOIN brands b ON a.brand_id = b.brand_id WHERE status = 1 AND a.archive = 0 AND (thumbnail IS NOT NULL OR thumbnail = '') AND DATE(date_sent) = '" + date + "' GROUP BY a.brand_id ORDER BY date_sent DESC LIMIT " + numSnapshots;
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
while (dbResult.Read())
{
snapshots.Add(new Snapshot
{
SnapshotId = Convert.ToInt32(dbResult["snapshot_id"]),
Guid = dbResult["snapshot_guid"].ToString().Replace("-", String.Empty),
BrandGuid = dbResult["brand_guid"].ToString(),
BrandName = HttpUtility.HtmlDecode(dbResult["name"].ToString()),
Subject = MyHelpers.Ellipsis(HttpUtility.HtmlDecode(dbResult["subject"].ToString()), 100),
DateTimeSent = Convert.ToDateTime(dbResult["date_sent"]),
Image = dbResult["image"].ToString(),
Status = Convert.ToInt32(dbResult["status"]),
Thumbnail = dbResult["thumbnail"].ToString()
});
}
dbResult.Close();
dbCmd.Dispose();
dbConn.Close();
return snapshots;
}
The problem I am having is that on the VIEW. It is returning the same dataset from GetEmailSnapshot. SO I am seeing the SAME 9 records from 8/10/2014 as an example.
Is there a reason why 8/10/2014 isn't being added to the list and then 8/9/2014 added in addition to the list?
I think I may have overcomplicated it. Here is the simplified version: FIXED
public PartialViewResult RecentEmails()
{
int days = 2;
List<HomeViewModel> viewModelList = new List<HomeViewModel>();
for (int count = 0; count < days; count++)
{
DateTime date = DateTime.Now.AddDays(count * (-1));
viewModelList.Add(new HomeViewModel
{
Date = date,
SnapshotItems = GetEmailSnapshot(9, date)
});
}
return PartialView(viewModelList.AsEnumerable());
}

Categories

Resources