Function which is use to take input data from HTML
function saveclickdata()
{
var allData = {
InvNo:document.getElementById('TbInvNo').value,
GrossSale:document.getElementById('TbOrderTotal').value,
discount:document.getElementById('TbDiscount').value,
CusCash:document.getElementById('TbCash').value,
CusBal:document.getElementById('TbBalance').value,
};
$.ajax({
url: "\Controllers\POSController.cs\SaveData",
type: 'POST',
data: allData,
success: function (res) {
alert("success");
},
error: function (err) {
alet("Error");
}
});
Api which is in controller used to post data
[HttpPost]
JsonResult SaveData(POSMater collection)
{
if (collection.InvNo.ToString() == null)
{
var LocalInvNo = (from b in db.TblPOSMasters select b).FirstOrDefault();
int MaxInvNo = Convert.ToInt32(LocalInvNo) + 1;
collection.InvNo = MaxInvNo;
TblPOSMaster master = new TblPOSMaster();
master.InvNo = collection.InvNo;
master.AddBy = 1;
master.AddDate = DateTime.Now;
master.CashStatus = "A";
master.CompId = 1;
//master.CreditAmt = collection.CreditAmt;
//master.CrCardNo = collection.CrCardNo;
master.CusCash = collection.CusCash;
master.CusId = 1;
master.GrossSale = collection.GrossSale;
db.TblPOSMasters.Add(master);
db.SaveChanges();
}
else
{
return Json(collection);
}
return Json(collection);
}
What should i do? My html button working properly but still not able to call api
I think you ought to use forward slashes (/) in your URL
Related
I'm trying to send data to the controller using this AJAX call of type POST but it's sending null values to the controller. Through this code I want to make new records in the Microsoft Dynamics 365 CRM database.
var formdata = new FormData();
var rowCount = $(".newRow").length;
var projectarray = [];
var datearray = [];
var amountarray = [];
for (var i = 0; i < rowCount; i++) {
projectarray[i] = $("#ProjectType_" + i).val();
datearray[i] = $("#ClaimExpenseDate_" + i).val();
amountarray[i] = $("#Amount_" + i).val();
}
formdata.append("projectarray", projectarray);
formdata.append("datearray", datearray);
formdata.append("amountarray", amountarray);
$.ajax({
url: "#Url.Action("SetClaimDetails", "Claim")",
type: "POST",
data: formdata,
processData: false,
contenttype: false,
success: function (data) {
debugger;
window.location.href = "ess/claim";
alert("Submit Successful!");
},
error: function (err) {
window.location.href = "";
alert("Submit Failed!");
}
});
Here is my controller method which is storing null values instead of the values passed by the AJAX call. And because of this I'm not able to create new records in the database.
public ActionResult SetClaimDetails(string projectarray, string datearray, string amountarray)
{
try
{
Entity item = new Entity("bam_expenseclaims");
item["bam_expdate"] = Convert.ToDateTime(datearray);
item["bam_amount"] = amountarray;
item["bam_project"] = new EntityReference("new_project", Guid.Parse(projectarray));
globalService.Connection.Create(item);
}
catch (Exception ex)
{
XmlConfigurator.Configure();
ILog log = LogManager.GetLogger("TechnicalErrorAppender");
log.Error(string.Empty);
throw ex;
}
return View(Constant.CLAIMPATH);
}
I have a simple web API with registration, login, and call API module. I want to call each functionality from Windows form application.
In web API, I use the following script in JavaScript to call login method:
self.login = function () {
self.result('');
var loginData = {
grant_type: 'password',
username: self.loginEmail(),
password: self.loginPassword()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).done(function (data) {
self.user(data.userName);
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
}).fail(showError);
}
my controller actions are as follows
// POST api/Account/AddExternalLogin
[Route("AddExternalLogin")]
public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);
if (ticket == null || ticket.Identity == null || (ticket.Properties != null
&& ticket.Properties.ExpiresUtc.HasValue
&& ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
{
return BadRequest("External login failure.");
}
ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);
if (externalData == null)
{
return BadRequest("The external login is already associated with an account.");
}
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// POST api/Account/RemoveLogin
[Route("RemoveLogin")]
public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result;
if (model.LoginProvider == LocalLoginProvider)
{
result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
}
else
{
result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(model.LoginProvider, model.ProviderKey));
}
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// GET api/Account/ExternalLogin
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
if (error != null)
{
return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
}
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
if (externalLogin == null)
{
return InternalServerError();
}
if (externalLogin.LoginProvider != provider)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
return new ChallengeResult(provider, this);
}
ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
externalLogin.ProviderKey));
bool hasRegistered = user != null;
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
}
else
{
IEnumerable<Claim> claims = externalLogin.GetClaims();
ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
Authentication.SignIn(identity);
}
return Ok();
}
// GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true
[AllowAnonymous]
[Route("ExternalLogins")]
public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
{
IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();
string state;
if (generateState)
{
const int strengthInBits = 256;
state = RandomOAuthStateGenerator.Generate(strengthInBits);
}
else
{
state = null;
}
foreach (AuthenticationDescription description in descriptions)
{
ExternalLoginViewModel login = new ExternalLoginViewModel
{
Name = description.Caption,
Url = Url.Route("ExternalLogin", new
{
provider = description.AuthenticationType,
response_type = "token",
client_id = Startup.PublicClientId,
redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
state = state
}),
State = state
};
logins.Add(login);
}
return logins;
}
I am using the following code in winform to call the login action:
HttpClient client = new HttpClient();
Uri baseAddress = new Uri("https://localhost:44305/");
client.BaseAddress = baseAddress;
ArrayList paramList = new ArrayList();
user u = new user();
u.username = username;
u.password = password;
paramList.Add(u);
HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result;
In the above code I tried to call controller actions but failed. To accomplish my goal even calling the JavaScript from winform app is fine.
HttpClient client = new HttpClient();
Uri baseAddress = new Uri("http://localhost:2939/");
client.BaseAddress = baseAddress;
ArrayList paramList = new ArrayList();
Product product = new Product { ProductId = 1, Name = "Book", Price = 500, Category = "Soap" };
Supplier supplier = new Supplier { SupplierId = 1, Name = "AK Singh", Address = "Delhi" };
paramList.Add(product);
paramList.Add(supplier);
HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result;
Following answer will helpfull to you
call web api from c sharp
I usually use HttpWebRequest and HttpWebResponce in cases like yours:
//POST
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json; charset=utf-8";
//probably have to be added
//httpWebRequest.ContentLength = json.Length;
//do request
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//write post data
//also you can serialize yours objects by JavaScriptSerializer
streamWriter.Write(json);
streamWriter.Flush();
}
//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//read
using (Stream stream = httpResponse.GetResponseStream())
{
using (StreamReader re = new StreamReader(stream))
{
String jsonResponce = re.ReadToEnd();
}
}
}
//GET
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";
//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//read
using (Stream stream = httpResponse.GetResponseStream())
{
using (StreamReader re = new StreamReader(stream))
{
String jsonResponce = re.ReadToEnd();
}
}
}
Also you sould read this SO answer
//GET
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://160.114.10.17:85/api/Inventory/GetProcessDataByProcessName?deviceCode=OvCHY1ySowF4T2bb8HdcYA==&processName=Main Plant");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";
//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//read
using (Stream stream = httpResponse.GetResponseStream())
{
using (StreamReader re = new StreamReader(stream))
{
String jsonResponce = re.ReadToEnd();
}
}
}
I'm developping a webApp with MVC.
I have a view with cirkles displaying a value and a slider,
when you slide the cirkles need to display the new value.
I send the new value with a POST from my AJAX call to the controller,
which does a minor calculation with the value and give it back to the view
so the cirkles can display the updated value.
However my view still keeps using the startvalue.
#model UGT.UI.Web.MVC.Models.BelastingViewModel
<script language="JavaScript">
var config1 = liquidFillGaugeDefaultSettings();
#{
teller = 1;
string naam_var = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam = "fillgauge" + teller;
naam_var = "gauge" + teller;
#: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
teller++;
}
}
function toonCirkels() {
#{
teller = 1;
naam = "fillgauge" + teller;
string naam_var2 = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam_var2 = "gauge" + teller;
// #: gauge1.update("#Html.DisplayFor(modelItem => cat.Value)");
// #: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
// #: #naam_var2.update("#Html.DisplayFor(modelItem => cat.Value)");
teller++;
}
//#:gauge1.update("500");
}
}
public class BelastingsController : Controller
{
private BegrotingsManager begrotingsManager = new BegrotingsManager();
private int gemeenteId = 54;
private double loon = 200;
private BelastingViewModel belastingen = new BelastingViewModel();
// GET: Belastings
public ActionResult Index()
{
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return View(belastingen);
}
[HttpPost]
public ActionResult Index(String loon)
{
this.loon = Double.Parse(loon);
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return new HttpStatusCodeResult(HttpStatusCode.OK);
// return RedirectToAction("Index");
}
namespace UGT.UI.Web.MVC.Models
{
public class BelastingViewModel
{
public IDictionary<Categorie, double> Belasting { get; set; }
}
}
d3.selectAll('.range').on('change', function () {
this.value = parseInt(this.value);
if (this.value < 0) this.value = 0;
else if (this.value > 5000) this.value = 5000;
var loon = this.value;
var loonString = "€" + loon;
d3.select('.range_value').html(loonString);
sendLoon(loon, loonString);
});
}
function sendLoon(loon, loonString) {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "/Belastings",
type: "POST",
data: JSON.stringify({ "loon": loon }),
success: function () {
// window.location.reload();
toonCirkels();
},
error: function () { }
});
}
The success of your Ajax call calls 'toonCirkels' which only contains razor generated code which is filled on page load. The content of this method never changes as it contains ONLY razor generated code and thus will always have the same logic with the same values.
I am working on a project in which I have used angularjs and mvc.I am passing data from angular js controller to my mvc controller by $http.post().For now I am using single object/json array to retreive data like this -public bool UpdateIssueDetails(IssueBO issue).But I want that if I could do like this public public bool UpdateIssueDetails(IssueBO issue,List lstMembersToNotify).I want to send two json arrays from ny angular js controller to my above mvc controller method.
angularjs controller code
$scope.saveIssueDetails = function (issue) {
var milestoneId = "";
var milestoneName = "";
if ($scope.selectedIssue.Milestone== undefined) {
milestoneId = "";
milestoneName = "";
} else {
milestoneId = $scope.selectedIssue.Milestone.Id;
milestoneName = $scope.selectedIssue.Milestone.Name;
}
var arrMembersToNotify = [];
var arrMembersToNotifyNew = [];
var iCount = 0;
$("#membersToNotify input[type=checkbox]:checked").each(function () {
arrMembersToNotify = $(this).val().split("~");
arrMembersToNotifyNew.push({ "UserId": arrMembersToNotify[0], "UserDisplayName": arrMembersToNotify[1], "Email": arrMembersToNotify[2] });
});
var issueDetails =
{
Id: issue.Id,
ProjectId: issue.ProjectId,
ProjectName: issue.ProjectName,
IssueStatusId: $scope.selectedIssue.Status.Id,
StatusName: $scope.selectedIssue.Status.Name,
IssuePriorityId: $scope.selectedIssue.Priority.Id,
PriorityName: $scope.selectedIssue.Priority.Name,
AssignedUserId: $scope.selectedIssue.AssignedTo.Id,
AssigneeDisplayName: $scope.selectedIssue.AssignedTo.DisplayName,
IssueCategoryId: $scope.selectedIssue.Category.Id,
CategoryName: $scope.selectedIssue.Category.Name,
DueDate: $scope.selectedIssue.DueDate,
OwnerUserId: $scope.selectedIssue.OwnedBy.Id,
OwnerDisplayName: $scope.selectedIssue.OwnedBy.DisplayName,
IssueTypeId: $scope.selectedIssue.Type.Id,
IssueTypeName: $scope.selectedIssue.Type.Name,
IssueResolutionId: $scope.selectedIssue.Resolution.Id,
ResolutionName: $scope.selectedIssue.Resolution.Name,
MilestoneId: milestoneId,
MilestoneName: milestoneName,
Estimation: $scope.selectedIssue.Estimation,
Progress: $scope.selectedIssue.Progress,
};
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/UpdateIssueDetails/';
$http.post(url, [issueDetails, arrMembersToNotifyNew]).success(function (data, status, headers, config) {
if (data != '' || data.length >= 0 || data == true) {
//$scope.selectedIssue = issue;
//$scope.showIssueDetails($scope.selectedIssue);
$scope.GetAssignedIssues();
}
else if (data == '' || data == false) {
$scope.selectedIssue = null;
} else {
$scope.errors.push(data.error);
}
});
};
mvc controller code
[HttpPost]
[AuthenticationRequired]
public bool UpdateIssueDetails(IssueBO issue,List<IssueNotification> lstMembersToNotify)
{
try
{
//var issueDetails = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(issueAllDetails[0].ToString());
//List<Dictionary<string, string>> membersToNotifyDetails = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(issueAllDetails[1].ToString());
var membersToNotify = lstMembersToNotify.Select(membersToNotifyDetail =>
new IssueNotification()
{
UserId =membersToNotifyDetail.UserId,
Email =
membersToNotifyDetail.Email,
UserDisplayName =
membersToNotifyDetail.UserDisplayName
}).ToList();
var newIssue = new IssueBO
{
OwnerUserId = issue.OwnerUserId,
OwnerDisplayName = issue.OwnerDisplayName,
LastUpdatedUserId = SessionItems.UserId,
LastUpdaterDisplayName = SessionItems.DisplayName,
LastUpdatedOn = DateTime.Now,
ProjectId = issue.ProjectId,
ProjectName = issue.ProjectName,
Id = issue.Id,
AssignedUserId = issue.AssignedUserId,
AssigneeDisplayName = issue.AssigneeDisplayName,
IssueStatusId = issue.IssueStatusId,
StatusName = issue.StatusName,
Progress = issue.Progress,
IssuePriorityId = issue.IssuePriorityId,
PriorityName = issue.PriorityName,
IssueTypeId = issue.IssueTypeId,
IssueTypeName = issue.IssueTypeName,
IssueCategoryId = issue.IssueCategoryId,
CategoryName = issue.CategoryName,
IssueResolutionId = issue.IssueResolutionId,
ResolutionName = issue.ResolutionName,
DueDate = issue.DueDate,
Estimation = issue.Estimation,
MilestoneId = issue.MilestoneId,
MilestoneName = issue.MilestoneName
};
var result = BLL.AdminLayer.UpdateIssueDetail(newIssue, membersToNotify);
return result.IsSuccessful && result.Result;
}
catch (Exception ex)
{
BLL.Base.BaseLayer.WriteApplicationLog(ex);
return false;
}
}
I am passing two json array from my angularjs controller like this-$http.post(url, [issueDetails, arrMembersToNotifyNew]).success(function (data, status, headers, config).But I am getting error trying this.Please suggest how to achieve this.Thanks
You need to pass data to the action by using JSON.stringify()
$http.post(url, JSON.stringify({ issue: issueDetails,
lstMembersToNotify: arrMembersToNotifyNew
});
Post it as properties of an object.
$http.post(url, { issue: issueDetails, lstMembersToNotify: arrMembersToNotifyNew });
This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});