Here is my jquery code:
<script type="text/javascript">
$("#submitfileform").submit(function () {
$.ajax({
type: 'POST',
contentType: 'application/html;charset=utf-8',
dataType:'html',
success:function (result) {
$('#tablepartialview').html(result);
},
error:function (xhr, status) {
alert(status);
}
})
});
</script>
and here is html.beginform,
#using (Html.BeginForm("PropertyColumnMap", "ImportFile", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form single-col",id="submitfileform"}))
{
<input type="file" name="uploadFile" id="uploadFile" value=""/>
<select id="assetlist" name="assetlist">
<option>...</option></select>
<input class="btn btn-primary" type="submit" value="Submit" id="submitfile"/>
}
<div id="tablepartialview">
</div>
What happens is, on submit, I get the partial view of the same page 'Index' in div-'tablepartialview', instead of another page 'PropertyColumnMap', which I want. After the ajax call is done,it redirects to action 'PropertyColumnMap', and then I get the view for PropertyColumnMap.
public ActionResult PropertyColumnMap(FormCollection f, HttpPostedFileBase uploadFile)
{
String fileid = Import(uploadFile);
var excel = new ExcelQueryFactory(Session[fileid].ToString());
excel.DatabaseEngine = DatabaseEngine.Ace;
var workSheetName = excel.GetWorksheetNames().Last();
var assetname = f["assetlist"].ToString();
Mapping(assetname, workSheetName, fileid);
return PartialView("PropertyColumnMap");
}
If its possible please include following js to your project
http://malsup.github.com/jquery.form.js
Then you can use
$("#submitfileform").ajaxSubmit({
type: 'POST',
success:function (result) {
$('#tablepartialview').html(result);
},
error:function (xhr, status) {
alert(status);
}
});
As you are using MVC, just switch your Html.BeginForm to use the Ajaxified Ajax.BeginForm instead.
It allows for many options including specifying the id of the target element to update (e.g. 'tablepartialview').
e.g.
#using (Ajax.BeginForm("PropertyColumnMap", "ImportFile", new AjaxOptions(){ HttpMethod = "POST", UpdateTargetId = "tablepartialview"}, new { enctype = "multipart/form-data", #class = "form single-col", id = "submitfileform" }))
{
<input type="file" name="uploadFile" id="uploadFile" value="" />
<select id="assetlist" name="assetlist">
<option>...</option>
</select>
<input class="btn btn-primary" type="submit" value="Submit" id="submitfile" />
}
<div id="tablepartialview">
</div>
You probably have to install the Ajax unobtrusive NuGet package to provide the wiring, but it is quite simple and does not require you to write any extra JQuery for the view.
Related
I have a file in my view
<form id="upload" enctype="multipart/form-data">
<input type="file" name="fileUpload" id="fileUpload" size="23" />
</form>
and an ajax request
$.ajax({
url: '<%=Url.Action("JsonSave","Survey") %>',
dataType: 'json',
processData: false,
contentType: "multipart/mixed",
data: {
Id: selectedRow.Id,
Value: 'some date was added by the user here :))'
},
cache: false,
success: function (data) {}
});
but there is no file in the Request.Files. Whats wrong with the ajax request?
Upload files using AJAX in ASP.Net MVC
Things have changed since HTML5
JavaScript
document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}
Controller
public JsonResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
System.IO.Stream fileContent = file.InputStream;
//To save file, use SaveAs method
file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
}
return Json("Uploaded " + Request.Files.Count + " files");
}
EDIT : The HTML
<form id="uploader">
<input id="fileInput" type="file" multiple>
<input type="submit" value="Upload file" />
</form>
AJAX file uploads are now possible by passing a FormData object to the data property of the $.ajax request.
As the OP specifically asked for a jQuery implementation, here you go:
<form id="upload" enctype="multipart/form-data" action="#Url.Action("JsonSave", "Survey")" method="POST">
<input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
<button>Upload!</button>
</form>
$('#upload').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
},
error: function(xhr, error, status) {
console.log(error, status);
}
});
});
public JsonResult Survey()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
// save file as required here...
}
return Json(new { UploadedFileCount = Request.Files.Count });
}
More information on FormData at MDN
You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.
Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.
I have a sample like this on vuejs version: v2.5.2
<form action="url" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<input type="file" class="image_0" name="FilesFront" ref="FilesFront" />
</div>
<div class="col-md-6">
<input type="file" class="image_1" name="FilesBack" ref="FilesBack" />
</div>
</form>
<script>
Vue.component('v-bl-document', {
template: '#document-item-template',
props: ['doc'],
data: function () {
return {
document: this.doc
};
},
methods: {
submit: function () {
event.preventDefault();
var data = new FormData();
var _doc = this.document;
Object.keys(_doc).forEach(function (key) {
data.append(key, _doc[key]);
});
var _refs = this.$refs;
Object.keys(_refs).forEach(function (key) {
data.append(key, _refs[key].files[0]);
});
debugger;
$.ajax({
type: "POST",
data: data,
url: url,
cache: false,
contentType: false,
processData: false,
success: function (result) {
//do something
},
});
}
}
});
</script>
If you posting form using ajax then you can not
send image using $.ajax method,
you have to use classic xmlHttpobject method for saving image,
other alternative of it use submit type instead of button
I am trying to get user input in button click.
When user insert number and press Check, it needs to return xml data type.
So in my controller I create function which will return a data for passing ID
[ResponseType(typeof(AKONTA))]
public IHttpActionResult GetAKONTA(string id)
{
AKONTA aKONTA = db.AKONTAS.Find(id);
if (aKONTA == null)
{
return BadRequest("Ne postoji A_KONTO pod tim rednim brojem");
}
return Ok(aKONTA);
}
And In my View I have following
<br /><br />
<form>
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<a asp-action="Index" class="btn btn-primary" id="aKonto" action="#Url.Action("GetAKONTA", "Akontas")">Provjeri</a>
</div>
</form>
And I want to create in btn click when user pass ID it needs to return XML data format.
SO far I create a JS function, but I don't know JavaScript and don't know the logic how to pass Controller Action Result to JS.
<script>
$(document).ready(function () {
$('#aKonto').click(function () {
document.getElementById("aKonto").onclick = function () {GetAKONTA()};;
});
});
</script>
If someone can help me I would be very thankful.
Cheers !
UPDATE
function aKontoSubmit() {
$.ajax({
type: "GET",
url: 'api/Akontas',
//data: { id: id },
dataType: "xml",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
**routeConfig**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AkontasWebApi
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Add Reference of Jquery, to try the ajax call method.
function aKontoSubmit() {
$.ajax({
type: "POST",
url: '/Akontas/GetAKONTA',
data: $('form').serialize(),
dataType: "json",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Error while inserting data");
}
});
}
Change you Link Code as Below
<a asp-action="Index" class="btn btn-primary" id="aKonto" onClick='return aKontoSubmit() '>Provjeri</a>
Or Else You Can try if you are using ASP.Net MVC Core Development
<form asp-action="GetAKONTA" asp-controller="Akontas" method="post">
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<input class="btn btn-primary" id="aKonto" type = "submit" value = "Provjeri" />
</div>
</form>
After a couple hours of debugging and searching I found that I forget to put
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
This is location where should redirect if item exsist in database
And URL call need to be modified as well
URL: "/api/Akontas/GetAKONTA",
function aKontoSubmit() {
$.ajax({
type: "GET",
URL: "/api/Akontas/GetAKONTA",
data: { id: $('#AkontasId').val() },
contentType: "data/xml; charset=utf-8",
success: function (result) {
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
Hi i want to post just a simple string to a controller action in asp.net mvc5.
Im trying to do this for hours and cant find a solution on how it works.
I have tried many different solutions without one of them working in how I want.
For hours...
I have a simple view:
#{
ViewBag.Title = "Rollen und Rechte";
}
<form>
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
<div id="mydiv"></div>
</form>
#section scripts {
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}
</script>
}
The thing is that the function is never called.
What is wrong here?
And... in the next step I want to update div id mydiv
How can I change that without return a complete view in the controller and force a reload?
Thanks in advance :)
You are missing a closing parenthesis right before your closing </script> tag:
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}**)**
</script>
instead of using button click event use the following
$(document).on("submit", "form", function (event) {
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (xhr, desc, err) {
}
})
}
you can use ajax.BeginForm of mvc
like this :
#using (Ajax.BeginForm("YourActionName", "YourControllerName", new AjaxOptions {
InsertionMode = InsertionMode.Replace, //target element(#mydiv) will be replaced
UpdateTargetId = "mydiv"
}))
{
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
}
<div id="mydiv"></div>
and in yourController :
public PartialViewResult YourActionName(string name)
{
return PartialView("_YourPartialView");
}
_YourPartialView is a partial View that you want to return replace it with "mydiv" And how to make it with VIEW is the same
if your partial view has a model you should do this :
return PartialView("_YourPartialView",yourModel);
like my title says, I have a problem where my MVC Controller alwas returns the JsonResult in an new window and don't return it back to the ajax success event.
I also tried to GET the data from the Controller via Ajax or change the contenttype to something like "application/json", but I always get a new window with my raw Json data. In my opinion, the problem has to be something with the controller or the javascript is unable to catch the json data.
It's also not a browser specific problem, I have this in every common browser.
Is there anything I miss or is it just weird?
Controller:
public JsonResult Update(ChangeUserInformationViewModel model)
{
var user = UserManager.FindById(User.Identity.GetUserId());
user = model.User;
UserManager.Update(user);
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
Ajax:
$(document).ready(function () {
$('#save-user-alert').click(function () {
$("#ChangeUserInformation").submit();
});
$('#save-user-alert').on("submit", function (event) {
event.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
contentType: "json",
success: function (resp) {
if (resp.success) {
swal("Goo Job!", "Yippii", "success");
};
},
error: function (resp) {
swal("Failes", "Upps.. something went wrong", "danger");
}
});
});
});
Html:
#using (Html.BeginForm("Update", "User", FormMethod.Post, new { id = "ChangeUserInformation" }))
{
<div class="form-group">
<label for="Username">Username</label>
#Html.TextBoxFor(x => x.User.UserName, new { #class = "form-control", value = Model.User.UserName, id = "Username" })
</div>
<div class="form-group">
<label for="FirstName">First Name</label>
#Html.TextBoxFor(x => x.User.Firstname, new { #class = "form-control", value = Model.User.Firstname, id = "FirstName" })
</div>
<div class="form-group">
<label for="LastName">Last Name</label>
#Html.TextBoxFor(x => x.User.LastName, new { #class = "form-control", value = Model.User.LastName, id = "LastName" })
</div>
}
<button class="btn btn-danger waves-effect waves-light btn-sm" id="save-user-alert">Click me</button>
Pleas help me!
Sebastian
You are gettting the JSON response in the browser because your code is not doing an ajax post, instead it is doing a normal form submit.
Why is it not doing the ajax submit ?
Because you do not have any code which says to do so. You are binding the submit event to the wrong element. You should bind it to the form, not the button.
$('#ChangeUserInformation').on("submit", function (event) {
event.preventDefault();
// do your ajax call
});
Now when user clicks the other button, it will call the submit event on the form and the above submit event handler will be invoked and it will make an an ajax call..
I think the problem is that you are using the form Submit for your ajax call.
Change your javascript code into this to remove the submit behavior:
$('#save-user-alert').click(function () {
event.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
contentType: "json",
success: function (resp) {
if (resp.success) {
swal("Goo Job!", "Yippii", "success");
};
},
error: function (resp) {
swal("Failes", "Upps.. something went wrong", "danger");
}
});
});
I have seen #Sparky's answer and sample jsFiddle to this question, and to my mind I have the right html and javascript in place, but still the browser is submitting the form.
I have this html:
#using (Html.BeginForm("Create", "ClientWarehouseRequest", FormMethod.Post, new { #class = "form-horizontal" }))
{
<!-- many form inputs here -->
<div class="buttons-wrap">
<input type="hidden" name="SubmitButtonValue" id="SubmitButtonValue" />
<input class="k-button" type="submit" value="Post" name="SubmitButton" />
#Html.ActionLink("Cancel", "Index", controllerName: null, routeValues: null, htmlAttributes: new { #class = "k-button", style = "vertical-align: bottom;" })
<input class="k-button" type="submit" value="Save" name="SubmitButton" />
</div>
}
with this javascript:
$(document).ready(function () {
$('form').validate({
submitHandler: function (form) {
var postingWindow = $("#postingDialogWindow").data("kendoWindow");
postingWindow.title("Posting Client Request...");
postingWindow.open();
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize()
})
.success(function (result) {
if (result.success) {
window.alerts.info(result.message, true);
window.location.replace(result.redirecturl);
}
else {
window.alerts.error(result.error);
}
})
.fail(function (result) {
//window.alerts.error(result);
var result = $.parseJSON(result.responseText);
window.alerts.error(result.errorMessage);
})
.always(function (data) {
postingWindow.close();
});
return false;
},
invalidHandler: function (event, validator) {
alert('invalid');
}
});
}
Yet when I click on the of the submit buttons, the browser is submitting the form as a full postback. I need the form to submit via the $.ajax call inside the validate() function instead. What am I missing?