Calling SaveChanges through Web service - javascript

I try to Save data in Db using EF6 through Web service , but it runs forever without any indicators to error .
My web method :
[System.Web.Script.Services.ScriptService]
public class FamilyRelationService : System.Web.Services.WebService
{
[WebMethod]
public int Update(int id, string name)
{
int result = -1;
try
{
using (HRCTX ctx = new HRCTX())
{
using (FamilyRelationRepository familyRelationRepo = new FamilyRelationRepository(ctx))
{
FAMILYRELATION family = familyRelationRepo.Find(id);
family.RELATION_NAME = name;
family.State = StateInterface.State.Modified;
familyRelationRepo.InsertOrUpdate(family);
result = ctx.Save();
}
}
}
catch (Exception ee)
{
throw;
}
return result;
}
}
My Calling function :
function Update(e) {
name = $("#txt_relation_name").val();
id = $("#lbl_relation_code").text();
$.ajax({
type: "POST",
url: "FamilyRelationService.asmx/Update",
data: "{'id':'" + id + "', 'name':'" + name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = response.d;
if (result > 0) {
$("#name", row).text(name);
row.removeClass("highlightRow");
CloseEditStudentDialog();
}
else {
alert('Error...');
}
},
failure: function (msg) {
alert(msg);
}
});
return false;
}
<input type="submit" id="btn_save" value="Save" onclick="Update(); return false;" />
In FireBug Console :
I see the following :

Related

Passing Javascript Object array to MVC Controller

I have these ViewModels:
public class UserAddRoleListViewModel
{
public String Id { get; set; }
public String Name { get; set; }
}
public class SaveUserNewRoleViewModel
{
[Required]
public String RoleId { get; set; }
public String RoleName { get; set; }
public List<UserAddRoleListViewModel> RoleList { get; set; }
}
How can I pass an array of objects that have a format like this:
var object = {
Id: rowIdItem,
Name: rowItem
};
dataSet.push(object);
to my MVC Controller here:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VerifyRole(SaveUserNewRoleViewModel Input)
{
IEnumerable<object> errors = null;
if (ModelState.IsValid)
{
if(Input.RoleList[0] != null)
{
foreach (var item in Input.RoleList)
{
if (Input.RoleId == item.Id)
{
ModelState.AddModelError("RoleId", "Role already exists");
errors = AjaxError.Render(this);
return Json(new { success = false, errors });
}
}
return Json(new { success = true });
}
return Json(new { success = true });
}
else
{
errors = AjaxError.Render(this);
return Json(new { success = false, errors });
}
}
So far it seems like its always passing an nothing when I debug it
EDIT:
Just to clarify. I can already pass the item via ajax. It's just that when I debug, RoleList is empty.
This is my ajax function:
$(document).on("submit", "#modal", function (e) {
e.preventDefault();
var selectedText = $("##Html.IdFor(m=>m.RoleId) :selected").text();
var selectedId = $("##Html.IdFor(m=>m.RoleId)").val();
var form_data = $(this).serializeArray();
form_data.push({ name: "RoleList", value: dataSet });
console.log(form_data);
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
$.ajax({
url: "#Url.Action("VerifyRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: form_data,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
if (result.success) {
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
return;
}
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
}
});
return false;
});
EDIT 2:
Added code that fills dataSet:
$(document).on($.modal.AFTER_CLOSE, function (event, modal) {
dataSet.push(object);
table.row.add(object).draw();
$("#modal").empty();
});
Javascript
$("#myBtn").click(function () {
var dataSet= [];
var obj = {
Id: rowIdItem,
Name: rowItem
};
dataSet.push(obj);
var data = {
"RoleId": '1',
"RoleName ": 'roleName',
"RoleList": dataSet
};
$.ajax({
type: "POST",
traditional:true,
url: "controller/VerifyRole",
content: "application/json;",
dataType: "json",
data: data ,
success: function () {
}
});
});
Controller/Action
[HttpPost]
public ActionResult VerifyRole(SaveUserNewRoleViewModel input)
{
...
}
Try this:)
$(document).on("submit", "#modal", function (e) {
e.preventDefault();
var selectedText = $("##Html.IdFor(m=>m.RoleId) :selected").text();
var selectedId = $("##Html.IdFor(m=>m.RoleId)").val();
var form_data = {};
form_data.RoleId = selectedId;
form_data.RoleName =selectedText;
console.log(form_data);
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
$.ajax({
url: "#Url.Action("VerifyRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
if (result.success) {
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
return;
}
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
}
});
return false;
});
my example with datasets:
$("body").on("click", "#btnSave", function () {
var ops = new Array();
$("#table TBODY TR").each(function () {
var row = $(this);
var ps = {};
ps.colname1 = row.find("TD").eq(0).html();
ps.colname2 = row.find("TD").eq(1).html();
ps.colname3= row.find("TD").eq(2).html();
ops.push(ps);
});
var item = {};
item.nam1 = "test";
item.List = ops;
$.ajax({
type: "POST",
url: " ...",
data: JSON.stringify(item),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
}
});
});

Pass javascript array to c# array/list using $.post without specifing datatype as json

I have a model created in javascript as follows
function Vehicle() {
this.type = 'Vehicle';
this.data = {
VehicleKey: null
}
};
I have a similar model created in c# as follows
public class Vehicle
{
public string VehicleKey { get; set; }
}
Now I am building an array of VehicleKeys in javascript as follows
function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = new Vehicle();
vehicleObject.data.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKey.push(vehicleObject.data);
}
return vehicleKeys ;
}
I am calling the $.post(url, data) as follows
var objectToSend = GetVehicleDetails(selectedVehicles);
var data = JSON.stringify({
'vehicles': objectToSend
});
$.post(url, data)
.done(function (result) {
if (result) {
download(result, 'VehicleReport.xlsx', { type: 'application/octet-stream' });
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function (error) {
console.log("Error creating report.");
});
The MVC Controller has a method to accept Vehicles with multiple VehicleKeys coming from javascript
public byte[] CreateVehicleReport(List<Vehicle> vehicles)
{
//Generation of report and pass it back to javascript
}
Here I am able to submit the data in javascript as 10 and 11 for Vehicles but when it catches the c#, the count is coming as 0.
Any help would be greatly appreciated.
$.post is not posted Content-Type json data so you need to use $.ajax
function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = {}; // Set Object
vehicleObject.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKeys.push(vehicleObject);
}
return vehicleKeys;
}
var objectToSend = GetVehicleDetails(selectedVehicles);
$.ajax({ type: 'POST',
url: url,
data: JSON.stringify(objectToSend),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('data: ' + data);
},
}).done(function () {
if (result) {
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function () {
console.log("Error creating report.");
});
C# Method
[HttpPost("CreateVehicleReport")]
public byte[] CreateVehicleReport([FromBody]List<Vehicle> vehicles)
{
return null;
//Generation of report and pass it back to javascript
}
I used a similar approach once but with ajax and it went like this:
fill your array directly with the properties inside your class as object { } make sure the names are exactly the same:
function GetVehicleDetails(inputarray) {
var data_Temp = [];
for (var i = 0; i < inputarray.length; i++) {
var _vehiclekey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
data_Temp.push({ VehicleKey : _vehiclekey });
});
return data_Temp;
}
var objectToSend = GetVehicleDetails(selectedVehicles);
var JsonData = JSON.stringify({ vehicles: objectToSend });
$.ajax({
type: "POST",
contentType: "application/json",
url: "/controllerName/actionName", //in asp.net using mvc ActionResult
datatype: 'json',
data: JsonData,
success: function (response) {
},
error: function (response) {
console.log(response);
}
});
And the ActionResult in the controller should look like this:
[HttpPost]
public ActionResult Create(List<Vehicle> vehicles)
{
//do whatever you want with the class data
}
I don't know if this is helpful for you but this always works for me and i hope it helps.

calling a c# class method from html page

Can we call a C# method in a class from a html page??
I have a class names Crud.cs
public class Crud
{
public String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
I want to call this method from a html page.I'm using a html page not a asp page.Is there any possibility to call without using ajax or if ajax also how could I call.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-3.2.1.js" type="text/javascript"></script>
</head>
<body>
<div style="align-content:center;">
<input type="text" id="HtmlName" />
<button id="btn_gen_html" onclick="createHtml()">Generate</button>
</div>
<div id="Msg"></div>
<div id="feedbackMsg"></div>
<script>
function createHtml() {
var name = document.getElementById("HtmlName").value;
$.ajax({
type: "POST",
url: "Crud.cs/generateFiles",
data: { name } ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else(val==1)
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
}
</script>
</body>
</html>
This is my code. Here I am not able to call generateFiles() method in crud class. Can I call so.And if I can How?
You can't call normal method. The method must be static and web method.
Try this:
public class Crud
{
[WebMethod]
public static String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
You are missing a controler in your project.
You try to retrieve data from a cs file without a controler (or a [WebMethod])? this is impossible.
Try looking for some MVC guides, Here is one from microsoft web site
You dont have to use all that ASP component that showen there, but you can see there how to retrieve data from the server to the client.
Basic syntax
<script type="text/javascript"> //Default.aspx
function myfunction() {
$.ajax({
type: "POST",
url: 'Default.aspx/myfunction',
data: "mystring",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
Default.aspx.cs
[WebMethod]
public static String myfunction(string name)
{
return "Your String"
}
If you want to use page call without ajax: Ref
//cs file (code behind)
[ScriptMethod, WebMethod]
public static string GetLabelText(string param1)
{
return "Hello";
}
//aspx page
<script type="text/javascript">
function InsertLabelData() {
PageMethods.GetLabelText(param1,onSuccess, onFailure);
}
function onSuccess(result) {
var lbl = document.getElementById(‘lbl’);
lbl.innerHTML = result;
}
function onFailure(error) {
alert(error);
}
InsertLabelData();
</script>
If you're using ASP.NET Web Forms, there is a WebMethodAttribute you can use instead of calling .cs file directly which unsupported by AJAX due to no URL routing enabled for normal classes. The web method must be declared as static:
// if you're using ASMX web service, change to this class declaration:
// public class Crud : System.Web.Services.WebService
public class Crud : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static String generateFiles(String name)
{
return generateHtml(name);
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
Then your AJAX call URL should be changed to this (note that the web method should be exist in code-behind file, e.g. Crud.aspx.cs or Crud.asmx.cs):
$.ajax({
type: "POST",
url: "Crud.aspx/generateFiles", // web service uses .asmx instead of .aspx
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
If ASP.NET MVC is used, use JsonResult to return JSON string as success result:
public class CrudController : Controller
{
[HttpPost]
public JsonResult generateFiles(String name)
{
return Json(generateHtml(name));
}
}
The AJAX call for the action method looks similar but the URL part is slightly different:
$.ajax({
type: "POST",
url: "Crud/generateFiles",
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
//Perfect solution
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
//PLEASE menntion [WebMethod] attribute on your method.

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

How to Parse Collection in JQuery

I have a IEnumerable Collection of Custom DataType that I'm sending to the Client.
I want to parse the collection in my JQuery method. Currently I'm getting value as "undefined". Below is my code:
Service:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<CustomData> GetSetting(long userId);
public IEnumerable<CustomData> GetSetting(long userId)
{
var tempData = Context.DialogSettings.Where(item => item.id == userId).ToList();
return tempData.Select(dialogSetting => new CustomData { KeyName = dialogSetting.KeyName, KeyValue = dialogSetting.KeyValue }).ToList();
}
[DataContract]
public class CustomData
{
[DataMember]
public String KeyName;
[DataMember]
public String KeyValue;
}
Client:
function LoadSetting() {
$.ajax({
type: "GET",
url: "SampleService.svc/GetSetting",
data: '{"userId": "' + 1 + '"}',
processData: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myHistoryList = data.d;
alert(myHistoryList); // here I'm getting value: undefined
},
error: function (result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
}
});
}
});
From the comments on the question I can safely presume that the following js code will work:
if(typeof data != 'undefined'){
alert(data[0].KeyName); //this will yield a value.
}
else
alert('Ok. This is weird');

Categories

Resources