Ajax call always fires error function call - javascript

I am looking to post the data using an ajax call from MVC to Post API. The data is successfully posted, but the ajax call always fires the error function alert.
View Page
<div class="input-group">
#Html.TextBoxFor(m => m.ConfirmVisitID, new { Class = "form-control input-circle-right", #readonly = "readonly", #id = "Cvid" })
</div>
//all the input fields comes here
<input value="Confirm" type="button" id="loccat" onclick="CheckPromotionalCode();">
Script
<script>
function CheckPromotionalCode() {
var jva = document.getElementById('Mid').value;
var cid = document.getElementById('Cvid').value;
var pname = document.getElementById('PatientName').value;
var datefrom = document.getElementById('SDate').value;
var dateend = document.getElementById('EDate').value;
var mc = document.getElementById('IsMC').value;
var dept = document.getElementById('IsDepartment').value;
var empl = document.getElementById('IsEmployee').value;
var depen = document.getElementById('IsDependent').value;
var res = document.getElementById('reason').value;
var remark = document.getElementById('rem').value;
$.ajax({
url: 'http://localhost:89522/Mc/McIssued',
data: JSON.stringify({ Mid: jva, Cvid: cid, PatientName: pname, SDate: datefrom, EDate: dateend, IsMC: mc, IsDepartment: dept, IsEmployee: empl, IsDependent: depen, reason: res, rem: remark }),
method: 'post',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
success: function (response) {
alert("Successfull");
window.location.href = response.Url;
},
error: function () {
alert("Not Successfull");
}
});
}
Controller
public ActionResult McIssued(string Cvid, string Mid, string SDate, string EDate, string reason, string rem, string IsMC, string IsDepartment, string IsEmployee, string IsDependent, string PatientName)
{
string url = "http://localhost:74523";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
McIssued mc = new McIssued()
{
MemberID = Mid,
ConfirmVisitID = Cvid,
ProviderID = PID,
CreateUserID = UserId,
StartDate = StrtDate,
EndDate = EndDate,
McType = reason,
Remarks = rem,
RecStatus = Rec,
ModifyUserID = ModifyUserId
};
HttpResponseMessage response = client.PostAsJsonAsync<McIssued>("api/Mc/InsertintoMcTxn", mc).Result;
System.Diagnostics.Debug.WriteLine(response);
response.ToString();
response.EnsureSuccessStatusCode();
var redirectUrl = new UrlHelper(Request.RequestContext).Action("IssueMC", "Mc");
return Json(new { Url = redirectUrl });
}
So, how can I overcome this issue? Any help would be appreciated. Thanks in advance

Related

AJAX Call passing null values to controller

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);
}

How to POST Data from HTML Page via WebApi in MVC Controller

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

How to call web API login action from Windows form app

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();
}
}
}

Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action

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);
}
});

Jqgrid ui autocompletion : Disable Case sensitivity

In my JQgrid i have a ui atocomplete column which are Case sensitive.
For example i have 2 Items in my grid: Ivan and ivan, if i type "i" autocomplete will return only ivan.
I have tryed to make a function inside of source: but i failed since my ajax call always return object Object instead of an item. Any ideas?
Code for autocomplete:
$(elem).autocomplete({
delay: 0,
minLength: 0,
source: function (req, response) {
alert(req);
$.ajax({
mtype: "post",
url: '#Url.Action("GetBrands")',
dataType: "json",
async: false,
cache: false,
data: { term: req },
success: function (data) {
alert(data);
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function (item) { return matcher.test(item.value); }));
}
});
},
Controller side code:
public virtual JsonResult GetBrands(string term)
{
if (term == null) term = string.Empty;
var vendorId = _service.GetVendorIdByUsername(GetUserName());
var brands = _service.GetBrandsByVendor(vendorId);
var brand = new BrandsViewModel();
brand.BrandName = "Opret ny Brand...";
brands.Add(brand);
foreach (var brandsViewModel in brands)
{
if (brandsViewModel.BrandName == "Intet")
{
brandsViewModel.BrandName = "";
}
}
return Json((from item in brands
where item.BrandName.Contains(term)
select new
{
value = item.BrandName
//votes = item.Votes,
}).ToArray(),
JsonRequestBehavior.AllowGet);
}
convert it all to one case when compering:
public virtual JsonResult GetBrands(string term)
{
if (term == null) term = string.Empty;
term = term.ToLower();
var vendorId = _service.GetVendorIdByUsername(GetUserName());
var brands = _service.GetBrandsByVendor(vendorId);
var brand = new BrandsViewModel();
brand.BrandName = "Opret ny Brand...";
brands.Add(brand);
foreach (var brandsViewModel in brands)
{
if (brandsViewModel.BrandName == "Intet")
{
brandsViewModel.BrandName = "";
}
}
return Json((from item in brands
where item.BrandName.ToLower().Contains(term)
select new
{
value = item.BrandName
//votes = item.Votes,
}).ToArray(),
JsonRequestBehavior.AllowGet);
}

Categories