Ajax jQuery not always executes action on Controller - c#

I have the Controller method below made in ASP.NET MVC 3 (C#) who returns a PartialView:
public ActionResult InsertEmail(long idPerson)
{
PersonEmailViewModel mail = new PersonEmailViewModel();
mail.email.Person_idPerson = idPerson;
return PartialView(mail);
}
The method that I need to execute on submit form is:
[HttpPost]
public ActionResult InsertNewEmail(PersonEmail mail)
{
mail.idPersonEmail = mail.Insert(mail);
return Json(mail);
}
My partialView contains this code:
#model PlatformLib_MySql.BLL.Person.PersonEmailViewModel
<form action="" id="frmNewEmail" method="post">
<div>
E-mail: #(Html.TextBoxFor(m => m.email.email))
#(Html.HiddenFor(m => m.email.Person_idPerson))
<input type="submit" value="Insert" id="btnSubmitMailInsert" />
<input type="button" value="Cancel" id="btnCancelMailInsert" />
</div>
</form>
In my JS file I run this code on #btnSubmitMailInsert button:
jQuery("#btnSubmitMailInsert").click(function () {
submitNewEmail();
window.location.reload();
});
function submitNewEmail() {
event.preventDefault();
var mail = {
email: jQuery("#frmNewEmail #email_email").val(),
Person_idPerson: jQuery("#frmNewEmail #email_Person_idPerson").val()
};
var request = jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false
});
request.done(function (msg) {
console.log(msg);
});
request.fail(function (msg) {
console.log(msg);
});
}
My problem is focused on Ajax request. Rarely I can make the "happy way", where on submit click, the event is activated on jQuery, calls the method "submitNewEmail()", that calls an Ajax, executes the method on controller and pass with success. But not so... It always returns with fail, not because error returned by controller method, but simply because ajax doesn't runs properly, doesn't execute the method on controller, even with a breakpoint inserted there (on VS2010).
In this JS code posted by me here is an attempt to alternatively solve this problem, unsuccessful.
The original code is:
jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false,
success: function (result) {
debugger;
jQuery("#tblEmail").append("<tr><td>Email inserido</td></tr>");
},
error: function () {
debugger;
alert("Erro ao inserir e-mail.");
}
});
I left the "console.log(msg)" temporary, just to solve this problem.
Can someone of you tell me what is happening, or to point where is my error?

I found the problem. Everything was right, but some detail damaged the code: window.location.reload();
I made some changes in my code, that looks like it:
jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false
}).done(function (data) {
// Do something
});
The another way is right too, the only relevant change was:
jQuery("#btnSubmitMailInsert").click(function () {
event.preventDefault();
submitNewEmail();
// window.location.reload // -> Commented for testing and everything worked fine.
});
Thanks for trying to help me. This helped me so much.

Related

ValidateInput(true) not working accepting html tags with ajax post call

I want to block HTML tags. I'm passing HTML tags to action and it is accepting it. I have used [ValidateInput(true)] but still its accepting HTML. By default, validation is enabled but in this case, it is not working
Im using ajax call to send data :
$.ajax({
method: "Post",
url: "/Home/MyAction",
contentType: 'application/json',
data: JSON.stringify({ htm: "<span>abc</span>"}),
success: function (d) {
UnBlockUI();
if ($.type(d) == "string")
AccessDenied();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
UnBlockUI();
ErrorMessage("Something went wrong, please try again");
}
});
The code:
[ValidateInput(true)]
public ActionResult MyAction(string htm)
{
return View(htm);
}
any solution to get rid of this problem
Thanks :)
#Biby Augustine is right....
Simply pass the Object and it validates donot do JSON.stringify() as it converts the object to valid json (string) which is not validated by ValidateInput annotation
$.ajax({
method: "Post",
url: "/Home/MyAction",
data: dataObject,
success: function (d) {
UnBlockUI();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
UnBlockUI();
ErrorMessage("Something went wrong, please try again");
}
});
ValidateInput validates if there any suspicious requests coming on Form submission.
Form submission means do post back of the entire form by click on a submit button.
For example
HTML:
<body>
<form id="frmDemo" method="post" action="/Home/Demo">
<input type="hidden" id="hdnText" value="<span>Testing</span>"/>
<button type="submit" form="frmDemo" value="Submit">Submit</button>
</form>
</body>
In ActionResult
[HttpPost,ValidateInput(false)]
public ActionResult Demo(FormCollection frm)
{
frm["hdnText"].ToString(); //this will give you the result
}
In case any html tag encountered while posting it will be blocked.

How to pass data to controller action from view in asp.net mvc?

I am creating an asp.net application.
I have an image displayed inside the view of a controller action. When I click on an item in the view (say an image) I would like to pass some data (say ID) to a controller action.
I have the following code in the view:
#Url.Content("ActionName", "Controller");
I would like to send the data into the ActionName action of the Controller controller.
And the controller action looks as follows:
public ActionResult ActionName(string someParam)
{
return View();
}
I can call the controller action without a problem but I cannot pass the data. Thanks for help.
<a href='#Url.Action("MyAction", "MyController", new {id = "ID"})'>
<img src='#Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>
You can Add image in URL action or create onclick function for image and make Ajax request
<a href="#Url.Action("ActionName", "Controller", new {someParam = "value"})">
<img />
</a>
you can make an ajax call
an example below
$('#btnSave').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});

Accessing request from external url

Hi I'm new to umbraco MVC. I'm using version 7. What I'm trying to do is following:
An External page www.ble1.com is posting to my page www.le2.com/recieve when that happens ble1 is posting to the page and in the browser dev tools I can see the Form Data name of the parameter (tok) and some encoded string.
Now I want to take this data and send it to the controller code behind the macro running on my page www.le2.com/recieve. How would this be possible? I'm used to workin in asp.NET where I have the pageLoad function in code behind but I'm confused how to tackle this in Umbraco MVC.
What I have done so far is Create cshtml:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '../../../umbraco/surface/land/Login',
data: JSON.stringify({}),
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data.d);
}
});
});
</script>
My Controller
public JsonResult Login()
{
//Don't know what to do here!!!!
//Everything that I have tryed has failed. Calling Request....etc.
}
I have never worked with Umbraco, but I have with MVC.
You Login method is not marked to receive POST requests. You need to use the attribute [HttpPost]
Your Login method does not have any Arguments, so, even if you fix your issue #1, it will not get any data.
So, first, you need some data in your Action Method, so you either need a ViewModel or a set or parameters, this is a ViewModel sample:
public class MyLoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
Now we use that ViewModel in the Action Method:
[HttpPost]
public JsonResult Login(MyLoginViewModel model)
{
if (ModelState.IsValid)
{
// Do something here (probably use Umbraco internal's authorization layer)
var valid = (model.UserName == "user" && model.Password == "pwd");
if (valid)
return Json(new { code = 0, message = "OK" });
else
return Json(new { code = 10, message = "User/Password does not match" });
}
// Model is invalid, report error
return Json(new { code = -1, message = "invalid arguments" });
}
It is a very naive example, it makes sure the ViewModel is Valid, if it is, it performs the actual login logic, in this sample is just checks 2 values and returns the status.
In the HTML page, you could have:
<input type="text" id="userName" />
<input type="text" id="password" />
<button id="login">Login</button>
<script>
$(document).ready(function () {
$("#login").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/home/Login',
data: JSON.stringify({ UserName: $('#userName').val(), Password: $('#password').val() }),
dataType: 'json',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert("An error has occurred while processing your request");
}
});
})
});
</script>
Again, very a naive example.
I hope it gives you enough information to adapt it to Umbraco.
Sorry I cannot give you Umbraco specific information.

Uploading a file to an ASPX server-side page

I'm having trouble understanding how to send an uploaded file's content to my ASPX server-side. This is for an HTML-4 implementation where File API isn't available on the client-side, and using .NET v4.0.
Here's what I have so far:
HTML on FileReceiver.aspx:
<input type="button" id="uploadFile" value="Upload" />
<div class="hidden">
<form id="uploadFileForm">
<input type="file" id="browseForFiles" />
</form>
</div>
(client-side) JS:
$("#uploadFile").click(function () {
$("#browseForFiles").click();
});
$("#browseForFiles").change(function () {
$("#uploadFileForm").submit();
});
$("#uploadFileForm").submit(function (e) {
// prevent default action
e.preventDefault();
// send file to server
$.ajax({
url: "FileReceiver.aspx/ReceiveFile",
type: "post",
dataType: "multipart/form-data", // <---- is this right?
data: ???, // <-------------------------- what goes here?
success: function(data) {
// do something on success
}
});
});
(Server-side) FileReceiver.aspx.cs:
[WebMethod]
public static string ReceiveFile(??? receivedFile) // <-- what type goes here?
{
// do something and return status
}
Please help fill in the two "???" in the codes above. Thanks in advance!
This should work
$("#uploadFileForm").submit(function (e) {
// prevent default action
e.preventDefault();
var formData = new FormData($('#uploadFileForm')[0]);
$.ajax({
url: "FileReceiver.aspx/ReceiveFile",
type: "POST",
// Form data
data: formData, // <-- see above to see where this comes from
dataType: "json", // <-- the dataType you're RETURNING, not sending
cache: false,
//Options to tell jQuery not to process data or worry about content-type.
contentType: false,
processData: false,
success: function(data) {
// do something on success
}
});
});
Then your C# code should look like this
[WebMethod]
public static string ReceiveFile(HttpPostedFileBase receivedFile)
{
// do something and return status
}

Calling a C# method with jquery

I am trying to call a method with jQuery on a button click.This is waht I have so far:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
[WebMethod]
public void AddToCartHack(string url)
{
GeneralHelperClass.URL = url;
}
What I am trying to do here is when I click the link with class add to cart I want to call the method AddToCartHack and pass it the curent URL as a parameter.
I must be doing something wrong because it seems that AddToCartHack is not being called.
What am I doing wrong?
There are quite a lot of issues with your code, I don't know where to start. So let's conduct an interactive refactoring session with you (if you don't care about my comments but just want to see the final and recommended solution, just scroll down at the end of answer).
First: you don't seem to be canceling the default action of the anchor by returning false from the .click() event handler. By not doing this you are actually leaving the browser perform the default action of the anchor (which as you know for an anchor is to redirect to the url that it's href attribute is pointing to. As a consequence to this your AJAX call never has the time to execute because the browser has already left the page and no more scripts are ever running). So return false from the handler to give your AJAX script the possibility to execute and stay on the same page:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
return false;
});
Second: You have specified contentType: 'application/json' request header but you are not sending any JSON at all. You are sending a application/x-www-form-urlencoded request which is the default for jQuery. So get rid of this meaningless parameter in your case:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
dataType: "json"
});
return false;
});
Third: You have specified that your server side code will return JSON (dataType: 'json') but your server side code doesn't return anything at all. It's a void method. In ASP.NET MVC what you call C# method has a name. It's called a controller action. And in ASP.NET MVC controller actions return ActionResults, not void. So fix your contoller action. Also get rid of the [WebMethod] attribute - that's no longer to be used in ASP.NET MVC
public class AccountController: Controller
{
public ActionResult AddToCartHack(string url)
{
GeneralHelperClass.URL = url;
return Json(new { success = true });
}
}
Fourth: you have hardcoded the url to the controller action in your javascript instead of using server side helpers to generate this url. The problem with this is that your code will break if you deploy your application in IIS in a virtual directory. And not only that - if you decide to modify the pattern of your routes in Global.asax you will have to modify all your scripts because the url will no longer be {controller}/{action}. The approach I would recommend you to solve this problem is to use unobtrusive AJAX. So you would simply generate the anchor using an HTML helper:
#Html.ActionLink(
"Add to cart",
"AddToCartHack",
"Account",
null,
new { #class = "AddToCart" }
)
and then unobtrusively AJAXify this anchor:
$('a.AddToCart').click(function () {
var link = document.URL;
$.ajax({
type: 'POST',
url: this.href,
data: { url : link }
});
return false;
});
Fifth: You seem to be employing some document.URL variable inside your .click() handler. It looks like some global javascript variable that must have been defined elsewhere. Unfortunately you haven't shown the part of the code where this variable is defined, nor why is it used, so I cannot really propose a better way to do this, but I really feel that there's something wrong with it. Or oh wait, is this supposed to be the current browser url??? Is so you should use the window.location.href property. Just like that:
$('a.AddToCart').click(function () {
$.ajax({
type: 'POST',
url: this.href,
data: { url : window.location.href }
});
return false;
});
or even better, make it part of the original anchor (Final and recommended solution):
#Html.ActionLink(
"Add to cart",
"AddToCartHack",
"Account",
new { url = Request.RawUrl },
new { #class = "AddToCart" }
)
and then simply:
$('a.AddToCart').click(function () {
$.ajax({
type: 'POST',
url: this.href
});
return false;
});
Now that's much better compared to what we had initially. Your application will now work even with javascript disabled on the page.
place script method this way as shown below
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Add Success and error function to check your ajax functionality
...
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
alert('success');
},
error:function(){
alert('error');
}
});
....
If this is Asp.Net webforms you will need to make the webmethod static or the method cannot be accessed through JavaScript.
$(document).ready(function () {
$.ajax({
url: "Testajax.aspx/GetDate",
data: "f=GetDate",
cache: false,
success: function (content) {
$('#tableData').append('My Dear Friend');
alert(content);
},
failure: function (response) {
alert("no data found");
}
});
});

Categories

Resources