Ajax Submits automatically be invoked in MVC - c#

I have a weird problem.. This is my jquery code
$("#btnRate").click(function (e) {
alert("tık");
e.preventDefault();
var electionId = '#Model.ElectionId';
var profileId = '#Model.ProfileId';
$.ajax({
url: "Profile/Vote", // '#Html.Action("Vote","Profile")',
// data: { electionId: electionId, profileId: profileId },
dataType: "json",
type: "POST",
error: function (error) {
alert('An error occured, please try again! ');
},
success: function (data) {
if (data != null && data.success) {
alert("s1");
alert(data.url);
alert("s2");
window.location = data.url;
} else {
alert('An error occured, please try again. ');
}
}
});
return false;
});
and this is the html side code
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input id="btnRate" type="submit" class="btn btn-default" value="Vote !" />
</div>
</div>
when the detail form is loaded, automatically be invoked as clicked btnRate button. But i do not click..
and this is vote action in profilecontroller
// [HttpPost]
[ChildActionOnly]
public JsonResult Vote() //(int profileId, int electionId)
{
EvoteServicesProviderClient service = new EvoteServicesProviderClient();
// var result= service.createPolls(electionId, profileId);
// if(result ==1)
// return Json(new { success = true, url = "/Home/ProfileStatistic?electionId=" + electionId }, JsonRequestBehavior.AllowGet);
// else
// return Json(new { success = false, url = "/Home/ProfileStatistic?electionId=" + electionId }, JsonRequestBehavior.AllowGet);
return null;
}
even i do not click, vote function is invoked by ajax.. What is the reason?
edit: this is exception
An exception of type 'System.Web.HttpException' occurred in
System.Web.dll but was not handled in user code
Additional information: Error executing child request for handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.

I solved the problem.. very interesting ..
I just deleted the comment
// '#Html.Action("Vote","Profile")',
and it works good now..
this is the last part..
$(document).ready(function () {
$("#btnRate").click(function(e) {
alert("geldi");
alert("tık");
e.preventDefault();
var electionId = '#Model.ElectionId';
var profileId = '#Model.ProfileId';
$.ajax({
url: '#Url.Action("Vote","Profile")',
data: { electionId: electionId, profileId: profileId },
dataType: "json",
type: "POST",
error: function (error) {
alert('An error occured, please try again! ');
},
success: function (data) {
if (data != null && data.success) {
alert("s1");
alert(data.url);
alert("s2");
window.location = data.url;
} else {
alert('An error occured, please try again. ');
}
}
});
return false;
});
});

Related

Asp.net core MVC and JQuery submit

I have this code(JQuery) in my View:
$("form").submit(function (e) {
e.preventDefault();
var form = this;
var link = '#Url.Action("Action", "Controller")';
var args = {
MyFVal: MyFVal.val(),
MySVal: MySVal.val()
};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
alert(data.acces);
if (data.acces) {
AllEnable();
form.submit();
}
else {
alert(data.erromessage);
}
},
error: function () {
alert("Error. Kontaktujte správce.");
}
});
});
When I gets submitted then I have this if in my save action.
if (Request.Form.ContainsKey("Insert"))
{
// do code that is supposed to run
}
else if (Request.Form.ContainsKey("Edit"))
{
// do another code
}
My problem is that because I submitted form by JQuery this if and elseif never gets executed.
Thanks for any help!
You might want to pass value for your requirements in Action condition. See operationType sample parameter
var obj = {
UniqueId: modelUniqueId.val(),
Name: modelName.val(),
operationType: $("[name=operationType]").val()
};
$.ajax({
type: "POST",
url: '/hrms/Class/Index',
data: obj,
success: function (result) {
if (result.success == true) {
createAndProcessPageAlert("success", result.message);
}
else {
createAndProcessPageAlert("error", result.message);
}
And in your Controller \ Action
[HttpPost]
public JsonResult Index(string operationType, ClassModel model)
{
var result = new HttpResponseModel<ClassModel>();
var user = Request.GetUserProfile();
if (operationType == "add")

Error while binding through ajax call

I am doing ajax call in Asp.Net MVC with this code
$.ajax({
type: "GET",
url: '#Url.Action("GetAllFacts", "Home")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[0].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[0].Content + "'</div></div></div></div>");
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[1].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[1].Content + "'</div></div></div></div>");
},
error: function () {
alert("Error");
}
});
This hits to my Get Method GetAllFacts() with following codes
[HttpGet]
public JsonResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(allData_Facts, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
}
return Json("false", JsonRequestBehavior.AllowGet);
}
This is my code which returns list with 2 data properly, but after that it is not going to success method it alerts error as per Ajax error function.
Where I am wrong?
Try by
Remove assembly reference System.Web.Mvc out of your project.
Use nuget to install System.Web.Mvc for you project.
Verify Web.config to make sure it have System.Web.Mvc assembly.
Run to check.
Good luck!
ajax:
$.ajax({
type: "GET",
url: '/Home/GetAllFacts',
dataType: "json",
success: function (data) {
if (data.success) {
// connect to server successful and everything's ok
// access to server returned data: data.alldata
} else {
// connect to server successful but something went wrong
alert(data.ex); // throw exception message
}
},
error: function () {
// connect to server failure
}
});
controller:
[HttpGet]
public ActionResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(new { success = true, alldata = allData_Facts }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
return Json(new { success = false, ex = e.Message }, JsonRequestBehavior.AllowGet);
}
}

Issue with TypeScript and controller

So I'm converting a site form VB to C# and using TypeScript in the process. I have it successfully passing the data to the controller, however the controller post back to the same page instead to the next page.
Here's the TypeScript (full module here)
function formSubmission(submitId, submitUrl, formData, validation) {
if (!submitId || hasSubmit)
return false;
if (validation) {
if (!$("#empApp form").validate().form())
return false;
hasSubmit = true;
}
hasSubmit = true;
// add load status functionality
$(".modal").modal("show");
$.ajax({
type: "POST",
url: submitUrl,
data: formData,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
window.location.href = "/employment/application/references";
},
error: function (xhr, ajaxOptions, error) {
$(".modal-body").html("<h3>" + status + "<small>" + error + "</small></h3>");
setTimeout(function () {
$(".modal").modal("hide");
}, 100);
window.location.href = "/employment/application/work-experience";
}
});
}
Here's the Controller (full here)
[HttpPost, Route("Work-Experience")]
public ActionResult WorkExperience(List<EmploymentApplicationWorkExperience> appExperience)
{
EmploymentApplication empAppSession = getApplication();
if (!HasSession()) { return InvalidAppSession(); };
SetupViewBag();
if (!empAppSession.Steps.HasFlag(EmploymentApplication.ApplicationStepTypes.EducationSkills))
{
return PartialView(GetApplicationStepError());
}
if (ModelState.IsValid)
{
if (appExperience != null)
{
empAppSession.ApplicationWorkEperiences = appExperience;
// empAppSession.Application.empApWorkExperiences = (ICollection<empApWorkExperience>)appExperience;
empAppSession.StepCompleted(EmploymentApplication.ApplicationStepTypes.Workexperiences);
updateApplicationStep(empAppSession.Steps);
updateApplicationWorkExpriences(empAppSession.ApplicationWorkEperiences);
updateApplication(empAppSession.Application);
return RedirectToAction("References");
}
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
else
{
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
}
Used a unnecessary filter on Controller that if not valid, would continue to return the current page. Once removed, page continued with out post back issue.

JavaScript stop working after AJAX call

My javascript is getting locked after ajax call.
When the user press enter then i call my c# method to search the city that the user typed, and then show the temperature, but when the search ends, the javascript stops working. And i found out that the error is on these lines:
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
code:
$(document).ready(function () {
$('#search-bar').keyup(function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $('#search-bar').val();
$.ajax({
url: '#Url.Action("getWeatherSearch", "Index")',
data: { city: city },
async: false,
complete: function (resp) {
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
Boxgrid.init();
}
});
} });
HTML:
<div align="center" class="div-search-bar">
#Html.TextBox("search-bar", "", new { #class = "search-bar", placeholder = "search" })
</div>
Try the following and see if it works for you:
$(function () {
var $searchbar = $('#search-bar'),
$grid = $('#rb-grid');
if ($grid.length) {
$searchbar.on('keyup', function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $searchbar.val();
$.ajax({
url: $.grid.data('weather-url'),
data: { city: city }
})
.done(function (resp) {
$grid.html(resp.responseText + $grid.html());
Boxgrid.init();
}
});
}
}
});
Add the following as a data attribute somewhere in your html, probably on your grid:
<div id='rb-grid' data-weather-url='#Url.Action("getWeatherSearch", "Index")'></div>

SyntaxError: JSON.parse: unexpected character error unexpected token <

i have a html button with "button-account" name in html body and want update aspx page with ajax when user click the button
I get this error in google chrom
SyntaxError: JSON.parse: unexpected character
and this in fire fox
SyntaxError: JSON.parse: unexpected character
Here's my Code
<script type="text/javascript" >
$(document).ready(function () {
$("#button-account").bind("click", "accountRegister");
function accountRegister() {
var waitObj = "<span class='wait' > <img src='Resource/Images/loading.gif' alt='' /> </span>";
var user = $("[name='username']").val();
var pass = $("[name='password']").val();
var dataObj = {
"username": user,
"password": pass,
};
$.ajax({
type: "POST",
url: "Checkout.aspx/login",
data: dataObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforSend: function () {
$(this).attr("disabled", "true");
$(this).after(waitObj);
},
success: function (msg) {
// Replace the div's content with the page method's return.
alert("success");
$("#checkout").slideUp("slow");
$("#payment-address").slideDown("slow");
},
error: function (msg) {
alert("error");
},
complete: function () {
$(this).attr("disabled", "false");
$(".wait").remove();
},
});
}
});
</script>
and here's my webmethod
[WebMethod]
public static string login()
{
//bool UserIsValid = false;
//string userName = "";
//string pass = "";
//MembershipUser u = Membership.GetUser(userName);
//pass = u.GetPassword();
//if (UserIsValid)
//{
// // returnAsHtml = "true";
//}
//else
//{
// //returnAsHtml = "use is not valid";
//}
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize("{ a:'1' }");
return result;
}
and fiddler return 200 status.
but return html. i know this is my mistake. how solve it?
any help is appriciate...
The server probably returns an error-page (e.g. "<html> ...") instead of the JSON response you expected.
Use fiddler, chrome's developer tools or a similar tool to check what the exact answer is, that the server returns.
In response to your comments:
Check what the content of the returned HTML page is. It's probably an error caused by your server-side code (e.g. an unhandled exception) or the server-side configuration.
Change this
var dataObj = {
"username": user,
"password": pass,
};
To this
var dataObj = {
"username": user,
"password": pass
};
You have an extra comma , ("password": pass,) after pass, so it is not able to serialize it properly.
Edit:
Try this
[WebMethod]
public static string login()
{
//bool UserIsValid = false;
//string userName = "";
//string pass = "";
//MembershipUser u = Membership.GetUser(userName);
//pass = u.GetPassword();
//if (UserIsValid)
//{
// // returnAsHtml = "true";
//}
//else
//{
// //returnAsHtml = "use is not valid";
//}
//JavaScriptSerializer js = new JavaScriptSerializer();
//string result = js.Serialize("{ a:'1' }"); // no need to serialize
return "{ a:'1' }";
}
so sorry!!!
in other section a called this
$('#button-login').live('click', function () {
$.ajax({
url: 'Checkout.aspx?login',
type: 'post',
data: $('#checkout #login :input'),
dataType: 'json',
beforeSend: function () {
$('#button-login').attr('disabled', true);
$('#button-login').after('<span class="wait"> <img src="Resource/Images/loading.gif" alt="" /></span>');
},
complete: function () {
$('#button-login').attr('disabled', false);
$('.wait').remove();
},
success: function (json) {
$('.warning, .error').remove();
if (json['redirect']) {
location = json['redirect'];
} else if (json['error']) {
$('#checkout .checkout-content').prepend('<div class="warning" style="display: none;">' + json['error']['warning'] + '</div>');
$('.warning').fadeIn('slow');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});

Categories

Resources