Error submitting form data asp.net MCV [duplicate] - c#

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
I'm new to front-end development and i'm trying to get a better understanding of front-end and how it connects with the back-end. Basically I am trying to submit a file to an action method in the back-end but for some reason it never hits the method.
Front-end:
<form id="Form2" name="Form2">
<input type="file" name="file" id="file" multiple />
<input type="submit" value="Upload" />
</form>
<script>
$(function () {
$("#Form2").submit(function (event) {
var formData = new FormData(this);
$.ajax({
url: "Property/UploadPropertyCSV",
type: 'POST',
datatype: 'json',
data: formData
}).done(function (data) {
alert(data);
});
});
});
</script>
Back end:
public ActionResult UploadPropertyCSV(HttpPostedFileBase file)
{
// bunch of processing
return Json(true);
}
Any ideas why this is happening?
Thanks in advance

im not really sure about your ajax method, but basically, I would do it like bellow :
$("#Form2").submit(function (event) {
var formData = new FormData(this);
$.ajax({
url: '#Url.Action("UploadPropertyCSV", "Property")',
type: 'POST',
datatype: 'json',
data: { file: formData},
success: function (result) {
alert(result);
}
})
});

Related

How to pass array HTML elements to AJAX POST to C# controller

I have this form in HTML.
<input type="text" id="myID">
<input type="text" id="myName[]">
<input type="text" id="myName[]">
myID field is used once while myName field is used multiple time in form. How can I pass the value of myName to AJAX? I am doing the following but it only works for myID and not myName
document.getElementById('myForm').onsubmit = function ()
{
var model = new FormData();
model.append("myID", $('#myID').val());
model.append("myName", $('#myName').val());
$.ajax({
url: "/MyController/MyMethod",
type: "POST",
data: model,
contentType: false,
processData: false,
success: function (response) {
Do_Something_Here;
},
error: function (xhr, error, thrown) {
alert(xhr.responseText);
}
});
}

Ajax Call not hitting controller when page is loaded

I have an ajax call that seems to be working fine on another page, however when i call it on this page it doesnt work.
CSHTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Script/jquery-1.12.2.min.js"></script>
<script src="~/Script/moment.js"></script>
<script type="text/javascript">
function qs(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
function initialiseForms() {
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).success(function (response) {
alert(JSON.stringify(response));
});
}
</script>
</head>
<body onload="initialiseForms()">
<h1 id="titleText"></h1>
<form id="evolveFormsForm" method="post" target="_self" action="Test">
<input type="hidden" id="formPackEventData" name="formPackEventData" value="" />
<input type="hidden" id="selectedTemplateCodes" name="selectedTemplateCodes" value="" />
<input type="hidden" name="logonMethod" value="automatic" />
</form>
</body>
</html>
Controller
public ActionResult Index()
{
return Json(new { success = true, rtn = "TEST" }, JsonRequestBehavior.AllowGet);
}
This alert(JSON.stringify(response)); works in the response but the breakpoint is not hit and the alert just displays an empty string.
Cheers
Shouldn't your ajax be like this?
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response)
{
alert(JSON.stringify(response));
},
success(function (response)
{
alert(JSON.stringify(response));
}
})
instead of
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).success(function (response) {
alert(JSON.stringify(response));
});
I feel like you have the success outside of the actual ajax as well as having an extra )
EDIT: An easy way for us to help you would be if you add a debugger; into the function itself and tell us if it throws an error in Google DevTools

receiving error (internal server error) when sending Ajax request on Asp.NET Web Forms Endpoint

I am sending ajax request in asp.net i get this error
POST http://localhost:1549/AdminArea/Roles.aspx/Create 500 (Internal
Server Error)
it is with Master Page Also shown code is in individual page Roles.aspx
my HTML Code
<form id="FormSave">
<input type="text" name="txtName" id="txtName" required="required"
class="form-control"/>
<input type="radio" name="Status" value="1" checked="checked"/> Active
<input type="radio" name="Status" value="0"/> In-active
</form>
Javascript Code For Sending Request
<script type="text/javascript">
$(document).ready(function () {
$("#BtnSave").click(function () {
var jsonText = JSON.stringify({ Name: $("txtName").val(), Status: $("Status").val() });
$.ajax({
type: "POST",
url: "Roles.aspx/Create",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function (response) {
alert(response);
}
});
});
});
</script>
SERVER SIDE C# SCRIPT /// IN Roles.aspx.cs file
[WebMethod]
public static string Create(string Name, string Status)
{
return "Hello " + Name + "With " + Status;
}
I want to alert this Hello Name With Status

Can't send a basic, non MVC form using ajax in .Net (C#)

I have seen answers to this question many times, but most of them are related to MVC controllers.
The issue I am having while trying to send a form using Ajax is that while in debug mode, the execution flow won't reach the break point I have in my code behind. Also, I notice that when I click in the submit button, the page refreshes very quickly; I though that the whole idea of ajax was to not refresh the page.
This is my index.aspx
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="ajaxform.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset class="fs1">
<input id="inputData" tabindex="1" name="theinputData" class="field" placeholder="Paste URL, docId or docSetId" runat="server"/>
<input id="form1Send" type="submit" class="button" onclick="submit()"/>
</fieldset>
</div>
</form>
</body>
Here is the code of my ajaxform.js
$(document).ready(function () {
$('#form1').submit(function (e) {
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
e.preventDefault();
});
});
Finally, here is my code behind
namespace mySpace
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string OnSubmit()
{
return "I was in code behind";
}
}
}
My break point is on the return line. Why the program never reach the WebMethod?
There are a couple of issues with your code:
You're double declaring something to handle the form. Your form1send button has onclick="submit()" in it as well as the form submit handler you're wiring up via jQuery
The content of your JavaScript handler is slightly off, for example you set contentType twice.
Here's a simplified version of the JavaScript that works on my machine:
$(document).ready(function () {
$('#form1').submit(function (e) {
$.ajax({
type: "POST",
url: "index.aspx/OnSubmit",
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
}
});
e.preventDefault();
});
});
NOTE: I based this (the content of the $.ajax call) on a code sample I found elsewhere, which is why the parameters and order of the parameters are different to yours.
If your app has a RouteConfig.cs file present, you may also need to change settings.AutoRedirectMode = RedirectMode.Permanent; to settings.AutoRedirectMode = RedirectMode.Off; if you see an HTTP 401 error in your browsers developer tools console for the request to your WebMethod decorated method in index.aspx.
By executing event.preventDefault() before FormData(this) a premature refresh is prevented.
See below:
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
});
});

Passing back JSON and input files to a controller MVC 4

I'm trying to pass my JSON object and two input file fields back to my MVC 4 controller from my view. If I set async: true, in my ajax I get the JSON object and no files. If I set my async: false, I get the files and no JSON.
Any ideas as to why I can't send everything back to my controller? I'm trying to upload images to my server.
Also as a side note, my JSON never returns success, it always errors, but the value is still passed to the controller when async: true,.
Any help would be great, thank you!
JSON:
var json = {Details:{"Name":"Person Name","Url":"http://stackoverflow.com/"};
AJAX:
$.ajax({
url: '/Admin/Create',
type: 'POST',
data: JSON.stringify(json),
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function () {
console.log('SUCCESS');
},
complete: function () {
console.log('COMPLETE');
}
});
Controller:
[HttpPost, ValidateInput(false)]
public ActionResult Create(AdminObjectModel jsonData,
IEnumerable<HttpPostedFileBase> images, IEnumerable<HttpPostedFileBase> small_images)
{
...
return Redirect("/admin/create");
}
HTML:
<form action="/Admin/Create" enctype="multipart/form-data" method="post">
...
<input type="file" id="images" class="span6" name="images" multiple />
...
<input type="file" id="small-images" class="span6" name="small_images" />
...
</form>
I think I figured out a solution, not sure if it's the best one, but it works.
View > AJAX:
$.ajax({
url: '/Admin/CreateJSON',
type: 'POST',
data: JSON.stringify(json),
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function () {
console.log('SUCCESS');
},
complete: function () {
console.log('COMPLETE');
}
});
View > HTML:
<form action="/Admin/Create" enctype="multipart/form-data" method="post">
...
<input type="file" id="images" class="span6" name="images" multiple />
...
<input type="file" id="small-images" class="span6" name="small_images" />
...
</form>
Controller:
private static AdminObjectModel create = new RecipeObjectModel();
[HttpPost, ValidateInput(false)]
public void CreateJSON(AdminObjectModel jsonData)
{
create = jsonData;
}
[HttpPost, ValidateInput(false)]
public ActionResult Create(IEnumerable<HttpPostedFileBase> images, IEnumerable<HttpPostedFileBase> small_images)
{
string t = create.Details.Name;
...
return Redirect("/admin/create");
}

Categories

Resources