DataTable equivalent in Jquery to store data? - c#

I have a form on which I am adding rows dynamically using Jquery.
Please take a look: DEMO
Now I want to save the data of all rows that has been added in my database using Jquery Ajax call on click event of SAVE button. The point where I am stuck is .. I am not sure how should I extract data of all rows and send it to the webmethod. I mean had it been c# I could have used a DataTable to store data of all rows before sending it to DataBase. I think I should create a string seperated by commas and pipe with data of each row and send it to webmethod. I am not sure if its the right approach and also how this is to be done (ie. creating such a string).
HTML
<table id="field">
<tbody>
<tr id="row1" class="row">
<td> <span class='num'>1</span></td>
<td><input type="text" /></td>
<td><select class="myDropDownLisTId"> <input type="text" class="datepicker" /></select></td><td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">Add Field</button>
<button type="button" id="deleteField">Delete Field</button>
<button type="button" id="btnsave">SAVE</button>

2 suggestions:
To keep it as close as what you already have, you could just enclose your table in a form tag, and then you could just submit the form (use something like the jQuery Form plugin to submit it via Ajax). The trickiest part will be to bind that data to action parameters. You may be able to receive it in the form of an array, or you could default to looping through properties of the Request.Form variable. Make sure you generate proper names for those fields.
I think the cleanest way to do it would be to have a JavaScript object holding your values, and having the table generated from that object, with 2-way bindings. Something like KnockoutJS would suit your needs. That way the user enters the data in the table and you'll have it ready to be Json-serialized and sent to the server. Here's a quick example I made.
I wouldn't recommend that approach, but if you wanted to create your own string, you could do something along those lines:
$("#btnsave").click(function () {
var result = "";
$("#field tr").each(function (iRow, row) {
$("td input", row).each(function (iField, field) {
result += $(field).val() + ",";
});
result = result + "|";
});
alert(result);
});
You will have problems if the users types in a comma. That why we use well known serialization formats.

use ajax call on save button event...
like this
$(document).ready(function () {
$('#reqinfo').click(function () {
// debugger;
var emailto = document.getElementById("emailid").value;
if (emailto != "") {
$.ajax({
type: "GET",
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto,
// data: dat,
Accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// debugger;
},
error: function (result) {
// debugger;
}
});
}
else {
//your validation message goes here
return false;
}
});
});
and add you all data in quesry string and transfer it to webservice..
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto + "data1=" + data1,

<script type="text/javascript">
var _autoComplCounter = 0;
function initialize3(_id) {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}
google.maps.event.addDomListener(window, 'load', initialize3);
function incrementValue() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
function GetDynamicTextBox(value) {
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
return '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "' + value + '" onkeypress = "calcRoute();" />' +
'<input type="button" class="superbutton orange" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
if (document.getElementById('number').value < 3) {
document.getElementById('number').value = value;
var div = document.createElement('DIV');
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var ht = '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "" onkeypress = "calcRoute();" class="clsgetids" for-action="' + _id + '" />' +
'<input type="button" class="superbutton orange" value="#Resources.SearchOfferRides.btnRemove" onclick = "RemoveTextBox(this); calcRoute();" />';
div.innerHTML = ht;
document.getElementById("TextBoxContainer").appendChild(div);
setTimeout(function () {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}, 100);
document.getElementById("TextBoxContainer").appendChild(div);
}
else {
alert('Enter only 3 stop point. !!');
}
}
function RemoveTextBox(div) {
//calcStopPointRoute();
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('number').value = value;
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
// window.onload = RecreateDynamicTextboxes;
</script>
And get the value from textbox:
#region stop point
string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
if (textboxValues != null)
{
for (Int32 i = 0; i < textboxValues.Length; i++)
{
if (textboxValues.Length == 1)
{
model.OptionalRoot = textboxValues[0].ToString();
}
else if (textboxValues.Length == 2)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
}
else if (textboxValues.Length == 3)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
model.OptionalRoot3 = textboxValues[2].ToString();
}
else
{
model.OptionalRoot = "";
model.OptionalRoot2 = "";
model.OptionalRoot3 = "";
}
}
}
#endregion

Short answer:
DataTable equivalent in javascript is Array of custom object (not exact equivalent but we can say that)
or
you roll your own DataTable js class which will have all the functions and properties supported by DataTable class in .NET
Long answer:
on client side(aspx)
you define a class MyClass and store all your values in array of objects of that class
and then pass that array after stingyfying it to web method
JSON.stringify(myArray);
on the server side(codebehind)
you just define the web method to accept a list of objects List<MyClass>
PS: When calling web method, Asp.net automatically converts json array into List<Object> or Object[]
Loooong answer (WHOLE Solution)
Page aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="App_Themes/SeaBlue/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
function MyClass(title,option,date) {
this.Title = title;
this.Option = option;
this.Date = date;
}
function GetJsonData() {
var myCollection = new Array();
$(".row").each(function () {
var curRow = $(this);
var title = curRow.find(".title").val();
var option = curRow.find(".myDropDownLisTId").val();
var date = curRow.find(".datepicker").val();
var myObj = new MyClass(title, option, date);
myCollection.push(myObj);
});
return JSON.stringify(myCollection);
}
function SubmitData() {
var data = GetJsonData();
$.ajax({
url: "testForm.aspx/PostData",
data: "{ 'myCollection': " + data + " }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("Success");
}
});
}
$(document).ready(function () {
filldd();
CreateDP();
var rowstring = "<tr class='row'><td class='number'></td><td><input type='text' class='title'/></td><td><select class='myDropDownLisTId'/><input type='text' class='datepicker'/></td><td><input type='submit'></input></td></tr>";
$("#addField").click(function (event) {
$("#field tbody").append(rowstring);
filldd();
CreateDP();
if ($("td").hasClass("number")) {
var i = parseInt($(".num:last").text()) + 1;
$('.row').last().attr("id", "row" + i);
$($("<span class='num'> " + i + " </span>")).appendTo($(".number")).closest("td").removeClass('number');
}
event.preventDefault();
});
$("#deleteField").click(function (event) {
var lengthRow = $("#field tbody tr").length;
if (lengthRow > 1)
$("#field tbody tr:last").remove();
event.preventDefault();
});
$("#btnsave").click(function () {
SubmitData();
});
});
function filldd() {
var data = [
{ id: '0', name: 'test 0' },
{ id: '1', name: 'test 1' },
{ id: '2', name: 'test 2' },
{ id: '3', name: 'test 3' },
{ id: '4', name: 'test 4' },
];
for (i = 0; i < data.length; i++) {
$(".myDropDownLisTId").last().append(
$('<option />', {
'value': data[i].id,
'name': data[i].name,
'text': data[i].name
})
);
}
}
function CreateDP() {
$(".datepicker").last().datepicker();
}
$(document).on('click', 'input[type="submit"]', function () {
alert($(this).closest('tr')[0].sectionRowIndex);
alert($(this).closest('tr').find('.myDropDownLisTId').val());
});
</script>
</head>
<body>
<form id="frmMain" runat="server">
<table id="field">
<tbody>
<tr id="row1" class="row">
<td>
<span class='num'>1</span>
</td>
<td>
<input type="text" class="title"/>
</td>
<td>
<select class="myDropDownLisTId">
</select>
<input type="text" class="datepicker" />
</td>
<td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">
Add Field</button>
<button type="button" id="deleteField">
Delete Field</button>
<button type="button" id="btnsave">
SAVE</button>
</form>
</body>
</html>
CodeBehind:
public partial class testForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void PostData(List<MyClass> myCollection)
{
Console.WriteLine(myCollection.Count);
}
}
public class MyClass
{
string title;
public string Title
{
get { return title; }
set { title = value; }
}
string option;
public string Option
{
get { return option; }
set { option = value; }
}
string date;
public string Date
{
get { return date; }
set { date = value; }
}
}
Hope this helps
References:
Json2.js file
stringify method
define a class in js

Related

How to call c# function in cshtml(razor page) from inside js function

How to call c# function in cshtml(razor page) from inside js function
this is cshtml code
#model TreeWithUnity.Pages.Tree.TreeExampleModel
<form method="post">
<input type="checkbox"
onclick="requestMyAction('#Model.tree_List[0].board_id', this.checked,
'loader-#Model.tree_List[0].dataName',#Model.tree_List[0]);" />
<div class="loader" style="display: none;" id="loader-#Model.tree_List[0].dataName">#Model.tree_List[0]
</div>
</form>
#section scripts{
<script type="text/javascript">
function requestMyAction(itemId, isChecked, loaderId,tn)
{
document.getElementById(loaderId).style.display = "inline-block";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
document.getElementById(loaderId).style.display = "none";
if (this.status === 200) {
document.getElementById(loaderId).style.display = "none";
}
}
};
var url = '#Url.Page("./TreeExample", "MyAction")';
xhr.open('POST', url);
xhr.setRequestHeader('RequestVerificationToken', '#Xsrf.GetAndStoreTokens(Model.HttpContext).RequestToken');
var data = new FormData();
data.append('itemName', itemId);
data.append('deploy', isChecked);
xhr.send(data);
#UpdateRecursiveData(tn)
}
}
</script>
}
#{
void UpdateRecursiveData(TreeWithUnity.Model.TreeNode tn)
{
if(tn.deployment)
{
<input type="checkbox"
onclick="requestMyAction('#tn.board_id', this.checked, 'loader-#tn.dataName');" />
<div class="loader" style="display: none;" id="loader-#tn.dataName">#tn.dataName</div>
<br />
for (int i = 0; i < tn.subTreeNodes.Count; i++)
RecursiveData(tn.subTreeNodes[i]);
}
}
}
#UpdateRecursiveData(tn) is not work
is it able to work in js c#func ?
I don't know how to implement this
UpdateRecursiveData should be executed later than MyAction of Tree Example. Is this possible?
how to call UpdateRecursiveData
public async Task<IActionResult> OnPostMyAction(string itemName,bool deploy)
{
if (TempData["TreeData"] != null)
tree_List = TempData.Get<List<TreeNode>>("TreeData");
TreeNode upTree=null;
foreach (var item in tree_List)
{
if (item.board_id == itemName)
{
upTree = item;
item.deployment = deploy;
}
}
if (deploy&&upTree.loadOn==false)
{
if(upTree!=null)
upTree.deployment = true;
IQueryable<tbl_tree> iqueryTree;
iqueryTree = _context.tbl_tree.Where(x => x.upcode == itemName);
var datas =await iqueryTree.ToListAsync();
for (int i = 0; i < datas.Count; i++)
{
TreeNode treeNode = new TreeNode(datas[i].name);
treeNode.board_id = datas[i].icd11;
tree_List.Add(treeNode);
}
TempData.Set("TreeData", tree_List);
}
return new OkResult();
}
Firstly,you cannot pass a js variable to c# function,you can try to use ajax to call c# handler,and handler returns html code,then put the html code to somewhere of the view.Here is a demo:
<form method="post">
</form>
<div id="data"></div>
#section scripts{
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: '?handler=UpdateRecursiveData',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: {id:1},
success: function (data) {
document.getElementById("data").innerHTML = data;
},
error: function (result) {
alert("fail");
}
})
})
</script>
}
handler:
public JsonResult OnPostUpdateRecursiveData(int id)
{
return new JsonResult("<div>id="+id+"</div>");
}
result:

JsTree Checkbox check Based on data-id

I want to check unchecked checkbox in based on data-id.
On drop down change i want to check unchecked checkbox in jstree.
I am Providing MY controller and Ajax Method bellow.
This is my jstree view.
Here is My Controller :
[HttpPost]
public ActionResult GetSingleUser(int id)
{
MachineShopDBEntities DB = new MachineShopDBEntities();
var SPresult = DB.GetSingleUser(id).FirstOrDefault();
return Json(SPresult);
}
Here is my Script:
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
$('.jstree-container-ul li[data-id=' + (i + 1) + ']').find('.jstree-anchor').addClass('jstree-clicked');
}
}
});
});
Here I created demo for you.
Make changes according to code snippet below
jQuery(function ($) {
$('.menux').jstree({
"core": { "check_callback": false },
"checkbox": { "keep_selected_style": false, "three_state": false, "tie_selection": false, "whole_node": false, },
"plugins": ["checkbox"]
}).bind("ready.jstree", function (event, data) {
$(this).jstree("open_all");
}).on("check_node.jstree uncheck_node.jstree", function (e, data) {
var currentNode = data.node;
var parent_node = $(".menux").jstree().get_node(currentNode).parents;
if (data.node.state.checked)
$(".menux").jstree().check_node(parent_node[0]);
else
$(".menux").jstree().uncheck_node(parent_node[0]);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.css" rel="stylesheet" />
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.5/jstree.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<div class="menux">
<ul>
<li>
Root node 1
<ul>
<li data-id="1"><a href="#" >Child node 1</a> </li>
<li data-id="2"><a href="#" >Child node 2</a></li>
<li data-id="3"><a href="#" >Child node 3</a></li>
<li data-id="4"><a href="#" >Child node 4</a></li>
<li data-id="24"><a href="#" >Child node 24</a></li>
</ul>
</li>
</ul>
</div>
Edit:
First make sure you have disable three-state while initializing jsTree as mentioned in above code snippet.
Try to implement above $('.menux li').each function in your code.
The below code is only sample to where you have to put this $('.menux li').each.
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
$('.menux li').each(function (index, value) {
var node = $(".menux").jstree().get_node(this.id);
var id = node.data.id;
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
if ((i + 1) == id) {
$(".menux").jstree().check_node(this.id);
}
}
}
});
});
});
If you got any error like jsTree is not a function then you can replace above $('.menux li').each function with this
$('.menux li').each(function (index, value) {
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
var dataid = $('#' + this.id).data('id');
if ((i + 1) == dataid) {
$('#' + this.id).find('.jstree-anchor').addClass('jstree-clicked');
}
}
}
});

Linq get data on load more button is click with start index and end index

i am using webApi and linq to get the data from SQL,Now i have Load More button in my page, when i click, it should bring 20 records each time,i am using has Start Index and End Index has my table column ID which is primary Key,when i click the load More Button, i ll get the last Id means last data ID from the list view, i am using that Id has my start index,now my problem is when i click on load more it brings 20 data but previous data has be erased, i need to get 20+20=40 data when i click my load more button for first time,how to achieve this.
//Linq//
public dynamic getALlImage(int userID, int LastImageID)
{
//here LastImageId is my Listview Last data ImageID
if (LastImageID!=0)
{
startIndex= LastImageID+20;
EndIndex=LastImageID-20;
}
else
{
startIndex= 20;
EndIndex=0;
}
GetAllListFields = (from user in dbContext.UserTable
join img in dbContext.ImageTable on user.userId equals img.userID into UserVoice
from Image in UserVoice.DefaultIfEmpty()
where (Image.imgId <= startIndex && Image.imgId >= EndIndex && Image.userID == userID && Image.IsStatusChecked == false)
orderby feeds.CreatedAt descending
select new
{
PostImage = Image == null ? 0 : Image.ImageID,
Image = usrMessae==null?0: Image.userMessage,
createdAt = feeds == null ? DateTime.UtcNow : feeds.CreatedAt,
UserId = userdata == null ? 0 : userdata.userId,
Name = userdata == null ? " " : userdata.Name,
username = userdata == null ? " " : userdata.userName,
Email = userdata == null ? " " : userdata.emailID,
}).Distinct().OrderByDescending(x => x.createdAt).Take(startIndex).ToList();
}
//HTML//
<div data-role="view">
<div>
<ul data-role="listview" data-bind="foreach:ImageList">
<li>
<div data-bind="text:userID"></div>
<div data-bind="text:userName"></div>
<div data-bind="text:UserImageSrc"></div>
<div data-bind="text:ImageId></div>
<div data-bind="text:PostImageSrc"></div>
<div >
<button data-bind="click:getLoadMoreImageData">Load More</button>
</div>
</li>
</ul>
</div>
</div>
//Knockout Js
function UserImageViewModel()
{
self=this;
var lastModelValue = (self.FeedPostdata()[self.FeedPostdata().length - 1]);
var lastPostImageId = (lastModelValue.ImageId())
//On Load More click last Image ID
self.getLoadMoreImageData=function()
{
$('#loading').show();
var UserModel = { userID:userID,ImageId:lastPostImageId}
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
url: serverUrl + 'api/xxx/xxx',
data: UserModel,
success: function (data) {
self.ImageList($.map(data, function (item) {
return new ImageModel(item);
}));},
complete: function () {
$('#loading').hide();
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);} });}}
// On Page Load without last Image ID
self.getALlUSerImage=function()
{
$('#loading').show();
var UserModel = { userID: userID}
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
url: serverUrl + 'api/xxx/xxx',
data: UserModel,
success: function (data) {
self.ImageList($.map(data, function (item) {
return new ImageModel(item);
}));},
complete: function () {
$('#loading').hide();
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);} });
}}
}
//Model//
function ImageModel(item)
{
self.userId=ko.observable(item.userId);
self.userName=ko.observable(item.UserName);
self.UserImageSrc = ko.computed(function () {
return "data:" + self.UserImageSrcType() + ";base64," + self.UserImageSrcBase64();});
self.ImageID=ko.observable(item.ImageId)
self.PostImageSrc = ko.computed(function () {
return "data:" + self.PostImageType() + ";base64," + self.PostImageBase64();});
}
$(document).ready(function () {
ViewModel = new UserImageViewModel();
ko.applyBindings(ViewModel);
}
How about something like this?
int Page = 1;
int RecordsPerPage = 10;
var q = yourQuery.Skip((Page - 1) * RecordsPerPage).Take(RecordsPerPage);

Table not refreshing using ajax

I an experimenting with MVC. I have a view which contains a dropdownlist and a table.
When I select an option from the dropdownlist, I want to get the data from my controller and update the view:
View:
<div>
<h2>Current Print Statistics</h2>
#using (Html.BeginForm())
{
#Html.DropDownList("LogTypes", new SelectList(Model.LogTypes, "Value", "Text"), new
{
id = "logType",
data_url = Url.Action("GetStatistics", "Home")
})
<table id="modelTable" class="table table-condensed">
<tr>
<th>RequestedOn</th>
<th>PrintedOn</th>
<th>Message</th>
<th>Success</th>
<th>TemplateName</th>
</tr>
<tbody>
#foreach (var item in Model.PrintLogs)
{
string css = (item.Success) ? "success" : "danger";
string link = (item.Success) ? "www.google.com" : string.Empty;
<tr class="#css">
<td>#item.RequestedOn</td>
<td>#item.PrintedOn</td>
<td>#item.Message</td>
#if (item.Success)
{
<td>#item.Success</td>
}
else
{
<td>#Html.ActionLink("False", "Index", "LogView", new { id = item.LogID }, null)</td>
}
<td>#item.TemplateName</td>
</tr>
}
</tbody>
</table>
}
</div>
</div>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$('#logType').change(function () {
console.log($(this).data('url'));
var selectedValue = $(this).val();
var table = $('#modelTable');
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
context: table,
data: { value: selectedValue },
success: function (result) {
$.each(result.PrintLogs,
function (index, log) {
$('<tr/>', {
html: $('<td/>', {
html: log.RequestedOn
}).after($('<td/>', {
html: log.PrintedOn
})).after($('<td/>', {
html: log.Success
})).after($('<td/>', {
html: log.Message
})).after($('<td/>', {
html: log.TemplateName
}))
}).appendTo(tableBody);
}
);
}
});
});
});
</script>
Controller:
[HttpGet]
public JsonResult GetStatistics(string value)
{
var request = LogTypeRequest.Last24H;
if (value == "0") request = LogTypeRequest.Last24H;
if (value == "1") request = LogTypeRequest.LastWeek;
if (value == "2") request = LogTypeRequest.LastMonth;
var model = new PrintServerModel
{
LogTypes = new List<ListItem>
{
new ListItem() {Text = "Last 24 Hours", Value = "0"},
new ListItem() {Text = "Last Week", Value = "1"},
new ListItem() {Text = "Last Month", Value = "2"}
},
PrintLogs = PrintServerService.GetPrinterLog(request)
};
return Json(model, JsonRequestBehavior.AllowGet);
}
Now when I try to debug in chrome, when the line $.ajax({ is reached it seems to jump to the end.
Ideally what I want is to display the data on start up and then when the user selects something from the dropdown, refresh the data.
Any help greafully appreciated!!
Odds are there is an error from the json call, you should add .done or error: to the end of it so you can see what your error is.
also there is a tab in chrome debug tool for watching the network calls, you may be able to see the response from the call in there with some additional details.
just looking over the ajax call, may want to change to have
data: JSON.stringify( { value: selectedValue }),
if you get more info i will do what i can to better my answer.

not able to display employee details in html table in view using json

I have got problem with displaying employee details in view when the user clicks the button on view..
when the user clicks the button the employee details(both id and name) will be called through the JSON and displaying data in html table, for that purpose I have written like this in my view
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<table id ="parenttable"></table>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
and this is my controller, here i am returning json data to view
namespace MvcSampleApplication.Controllers
{
public class EmpDetailsController : Controller
{
[HttpGet]
public ActionResult GetEmployees()
{
List<EmployeeClass> employees = new List<EmployeeClass>();
EmployeeClass employee1 = new EmployeeClass { EmployeeId=1, EmployeeName = "Rams"};
EmployeeClass employee2 = new EmployeeClass { EmployeeId = 2, EmployeeName = "joseph" };
EmployeeClass employee3 = new EmployeeClass { EmployeeId = 3, EmployeeName = "matt" };
employees.Add(employee1);
employees.Add(employee2);
employees.Add(employee3);
return Json(employees, JsonRequestBehavior.AllowGet);
}
}
}
but I am getting http 404 resource not found error, when i am trying to access this url
http://localhost/EmpDetails
would any one pls suggest any ideas and any suggestions on this,that would be very greatful to me..
Many thanks...
Modified View
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = #Url.Action("GetEmployees","EmpDetails")
//alert("hi");
$.getJSON(url, function (data) {
//alert("hi");
$.each(data, function (Val) {
var user = '<tr><td>' + Val.EmployeeId + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false;
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<div class="temptable">
<table id ="parenttable"></table>
</div>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
I am not able to hit second Alert Function inside JavaScript function.
You forgot to cancel the default action of the button by returning false from the click handler:
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false; // <!-- This is very important
});
By not canceling the default action, when you click on the submit button, the browser submits the form and redirects away from the page to the action of the form leaving no time for the AJAX request to ever execute.
Try using this as your url #Url.Action("GetEmployees","EmpDetails")
Try this
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
$.ajax({
url: 'GetEmployees',
type: 'POST',
data: JSON.stringify({ table: table }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var rowcount = data.employees.length;
for (var i = 0; i < rowcount; i++) {
var user = '<tr><td>' + employees[i].EmployeeId + employees[i].EmployeeName + '<tr><td>'
table.append(user);
}
});
},
error: function () {
alert('fail');
}
});
return false;
});

Categories

Resources