I'm new to AJAX, and I don't understand, why my data was not sent to controller.
So, on my View I have two input forms and a button:
HTML:
<input type="text" name="AddName">
<input type="text" name="AddEmail">
<button class="btn btn-mini btn-primary" type="button" name="add_btn" onclick="DbAdd()">Add</button>
I need after button "add_btn" clicked take data from these two inputs and send them to controller.
JavaScript:
<script type="text/javascript">
function DbAdd()
{
// Get some values from elements on the page:
var $form = $(this),
addedName = $form.find("input[name='AddName']").val(),
addedEmail = $form.find("input[name='AddEmail']").val();
$("#UserTable").html("<div>Please Wait...</div>");
$.ajax(
{
type: "POST",
url: "Save",
data:
{
name: addedName, email: addedEmail,
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
And this is my controller's method "Save" (I need to save data got from ajax to my DB):
[HttpPost]
public ActionResult Save(User userinfo)
{
string message = "";
using (var uc = new UserContext())
{
uc.UserList.Add(userinfo);
uc.SaveChanges();
message = "Successfully Saved!";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message };
}
else
{
ViewBag.Message = message;
return View(userinfo);
}
}
The problem is that when I put a break point to my controller's method, I don't receive data from ajax, null's only. So I add an empty record to DB.
Any suggestions?
Looks like $form.find("input[name='AddName']").val() and $form.find("input[name='AddEmail']").val() both return null. You should use $("input[name='AddName']").val() and $("input[name='AddEmail']").val() instead. Change the definition of DbAdd() to below
<script type="text/javascript">
function DbAdd()
{
// Get some values from elements on the page:
var addedName = $("input[name='AddName']").val(),
addedEmail = $("input[name='AddEmail']").val();
var user = { Name: addedName, Email: addedEmail };
$("#UserTable").html("<div>Please Wait...</div>");
$.ajax(
{
type: "POST",
url: "Save",
data: JSON.stringify({ userinfo: user }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
</script>
There is an extra comma which may be causing syntax error:
data:
{
name: addedName, email: addedEmail, //<------------ here
}
and pass data like this:
var userinfo = { name: addedName, email: addedEmail };
data: JSON.stringify(userinfo)
Also you should see : Posting JavaScript objects with Ajax and ASP.NET MVC
Related
How do I pass a whole set model object through formdata and convert it to model type in the controller?
Below is what I've tried!
JavaScript part:
model = {
EventFromDate: fromDate,
EventToDate: toDate,
ImageUrl: imgUrl,
HotNewsDesc: $("#txthtDescription").val().trim(),
};
formdata.append("model",model);
then pass it through AJAX, it will be a string, and if I check the value of Request.Form["model"] the result will be same, that is it will be received as string and value will be "[object object]"
Is there any way to pass model through formdata and receive it in the controller?
If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using
var formdata = new FormData($('form').get(0));
This will also include any files generated with <input type="file" name="myImage" .../>
and post it back using
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
and in your controller
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase)
[HttpPost]
public ActionResult YourActionName(YourModelType model, HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
formdata.append('someProperty', 'SomeValue');
If you want to send Form data using Ajax.This is the way to send
var formData = new FormData();
//File Upload
var totalFiles = document.getElementById("Iupload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("Iupload").files[i];
formData.append("Document", file);
}
formData.append("NameCode", $('#SelecterID').val());
formData.append("AirLineCode", $('#SelecterID').val());
$.ajax({
url: "/Controller/ActionName",
type: "POST",
dataType: "JSON",
data: formData,
contentType: false,
processData: false,
success: function (result) {
}
})
Using Pure Javascript, considering you have
<form id="FileUploadForm">
<input id="textInput" type="text" />
<input id="fileInput" type="file" name="fileInput" multiple>
<input type="submit" value="Upload file" />
</form>
JS
document.getElementById('FileUploadForm').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]);
}
//text value
formdata.append("textvalue",document.getElementById("textInput").value);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/UploadFiles');
xhr.send(formdata); // se
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//on success alert response
alert(xhr.responseText);
}
}
return false;
}
in your C# controller you can get values it as below
[HttpPost]
public ActionResult UploadFiles(YourModelType model, HttpPostedFileBase fileInput)
{
//save data in db
}
Reference : File Uploading using jQuery Ajax or Javascript in MVC
In view side ,if you are using ajax then,
$('#button_Id').on('click', function(){
var Datas=JSON.stringify($('form').serialize());
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
url: '#Url.Action("ActionName","ControllerName")',
data:Datas,
cache: false,
dataType: 'JSON',
async: true,
success: function (data) {
},
});
});
In Controller side,
[HttpPost]
public ActionResult ActionName(ModelName modelObj)
{
//Some code here
}
I create a survey. For whole survey I have only View and for every question partial view. Also I have a pagination. All these demonstrated in the picture below.
Now people can post the form (whole question) to server using GetAnswersMulti method. (I need the form be posted asynchronously). I want to add a feature - when person see the last not answered question - button changes from Answer to Answer and exit. I suppose to do it by removing one button and add another with specific Url. The problem is - server should check if this question is last.
I try to call corresponding method in controller asynchronously and get the returned value.
I tried much from SO and there is what I came to:
View
<script>
function isLast(data) {
$.ajax({
type: "POST",
url: "#Url.Action("Survey", "IsLastQuestion")",
data: { idQuestion: data },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
if (msg == "True") {
$(".submitbutton").remove();
}
},
error: function (e) {
alert("Fail");
}
});
}
</script>
#using (Html.BeginForm("GetAnswersMulti", "Survey", FormMethod.Post))
{
<input value="Ответить" type="submit"
class="btn btn-default submitbutton"
onclick="isLast(#Model.FirstOrDefault().IdQuestion);" />
}
Controller
[HttpPost]
public ActionResult IsLastQuestion(int idQuestion)
{
Question question = Manager.GetQuestion(idQuestion);
List<Question> questions = Manager.SelectQuestions(question.idAnketa);
if (questions.Count == Manager.GetCountQuestionsAnswered(question.idAnketa, SessionUser.PersonID))
return new JsonResult() { Data = true };
else
return new JsonResult() { Data = false };
}
[HttpPost]
public void GetAnswersMulti(List<PossibleAnswerVM> possibleAnswers)
{
List<Answer> answers = new List<Answer>();
foreach (PossibleAnswerVM possibleAnswer in possibleAnswers)
{
Answer answer = new Answer();
answer.datetimeAnswer = DateTime.Now;
answer.idOption = possibleAnswer.IdOption;
answer.idPerson = SessionUser.PersonID;
if (possibleAnswer.IsChecked)
{
if (IsValid(answer))
answers.Add(answer);
}
}
Manager.SaveAnswers(answers,possibleAnswers.FirstOrDefault().IdQuestion, SessionUser.PersonID);
}
Now method in controller is called and idQuestion is passed. Method in controller returns true (when it IS the last question). Then I get fail in js code.
Help me with this please. I searched 2 days through SO but didn't find anything that works for me.
Maybe better to use Html.Beginform() and use this script:
<script>
function isLast(data) {
$.ajax({
type: "POST",
url: "#Url.Action("Survey", "IsLastQuestion")",
data: { idQuestion : data},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg){
alert($.parseJSON(msg.d));
if (msg == "True") {
$(".submitbutton").remove();
}
},
error: function (e) {
alert("Fail");
}
});
}
</script>
#using (Html.BeginForm("GetAnswersMulti", "Survey", FormMethod.Post)
<input type="text" id="commentText" placeholder="Введите коментарий"/>
<input value="Ответить" type="submit"
class="btn btn-default submitbutton"
onclick="isLast(#Model.FirstOrDefault().IdQuestion);" />
}
In order for your action to return Json, then the return type of the action needs to be Json. Since the action returns a boolean value (true or false), then it is not considered as an action method. It needs to return an ActionResult type like so
public ActionResult IsLastQuestion(int idQuestion)
{
Question question = Manager.GetQuestion(idQuestion);
List<Question> questions = Manager.SelectQuestions(question.idSurvey);
if (questions.Count == Manager.GetCountQuestionsAnswered(
question.idSurvey,SessionUser.PersonID))
return Json(new{ d = true});
else
return Json(new{ d = false});
}
Notice that when I return Json like so return Json(new{ d = true});, there is an anonymous variable d which is the boolean value you will check in your success function like this
success: function (msg){
alert($.parseJSON(msg.d));
if (msg.d === true) {
$(".submitbutton").remove();
}
else if(msg.d == false){
// Do something if false retured.
}
}
Can you try like this?
[HttpGet]
public ActionResult IsLastQuestion(int idQuestion)
{
Question question = Manager.GetQuestion(idQuestion);
List<Question> questions = Manager.SelectQuestions(question.idSurvey);
if (questions.Count == Manager.GetCountQuestionsAnswered(question.idSurvey, SessionUser.PersonID))
return Content("True", "application/json" );
else
return Content("False", "application/json" );
}
In your ajax call-
function isLast(data) {
$.ajax({
type: "GET",
url: "#Url.Action("Survey", "IsLastQuestion")",
data: { idQuestion: data },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result)
{
//check the value inside result here..
},
error: function (e) {
alert("Fail");
}
});
}
Parameter is needed in IsLastQuestion function and you dont pass it in script.
function isLast(parameter) {
$.ajax({
type: "POST",
url: "#Url.Action("Survey", "IsLastQuestion")",
data: "{parameter}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg){
alert($.parseJSON(msg.d));
},
error: function (e) {
alert("Fail");
}
});
if (isLast2 == true) {
$(".submitbutton").remove();
}
}
How do I pass a whole set model object through formdata and convert it to model type in the controller?
Below is what I've tried!
JavaScript part:
model = {
EventFromDate: fromDate,
EventToDate: toDate,
ImageUrl: imgUrl,
HotNewsDesc: $("#txthtDescription").val().trim(),
};
formdata.append("model",model);
then pass it through AJAX, it will be a string, and if I check the value of Request.Form["model"] the result will be same, that is it will be received as string and value will be "[object object]"
Is there any way to pass model through formdata and receive it in the controller?
If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using
var formdata = new FormData($('form').get(0));
This will also include any files generated with <input type="file" name="myImage" .../>
and post it back using
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
and in your controller
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase)
[HttpPost]
public ActionResult YourActionName(YourModelType model, HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
formdata.append('someProperty', 'SomeValue');
If you want to send Form data using Ajax.This is the way to send
var formData = new FormData();
//File Upload
var totalFiles = document.getElementById("Iupload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("Iupload").files[i];
formData.append("Document", file);
}
formData.append("NameCode", $('#SelecterID').val());
formData.append("AirLineCode", $('#SelecterID').val());
$.ajax({
url: "/Controller/ActionName",
type: "POST",
dataType: "JSON",
data: formData,
contentType: false,
processData: false,
success: function (result) {
}
})
Using Pure Javascript, considering you have
<form id="FileUploadForm">
<input id="textInput" type="text" />
<input id="fileInput" type="file" name="fileInput" multiple>
<input type="submit" value="Upload file" />
</form>
JS
document.getElementById('FileUploadForm').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]);
}
//text value
formdata.append("textvalue",document.getElementById("textInput").value);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/UploadFiles');
xhr.send(formdata); // se
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//on success alert response
alert(xhr.responseText);
}
}
return false;
}
in your C# controller you can get values it as below
[HttpPost]
public ActionResult UploadFiles(YourModelType model, HttpPostedFileBase fileInput)
{
//save data in db
}
Reference : File Uploading using jQuery Ajax or Javascript in MVC
In view side ,if you are using ajax then,
$('#button_Id').on('click', function(){
var Datas=JSON.stringify($('form').serialize());
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
url: '#Url.Action("ActionName","ControllerName")',
data:Datas,
cache: false,
dataType: 'JSON',
async: true,
success: function (data) {
},
});
});
In Controller side,
[HttpPost]
public ActionResult ActionName(ModelName modelObj)
{
//Some code here
}
I need to pass my upload file to my controller using jquery ajax.
JS:
$('#btnpopupreg').click(function () {
$.ajax({
type: 'POST',
url: '/Membership/Register',
data: $('#frmRegister').serializeArray(),
dataType: 'json',
headers: fnGetToken(),
beforeSend: function (xhr) {
},
success: function (data) {
//do something
},
error: function (xhr) {
}
})
})
View:
#model Test.RegisterViewModel
#{
using Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "frmPopUpRegister", .enctype = "multipart/form-data"})
}
<input type="file" />
//rest of my strongly typed model here
<input type="button" value="BUTTON" />
//rest of the code here
Controller:
[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]
public void Register(RegisterViewModel model)
{
if (Request.Files.Count > 0) { //always 0
}
if (ModelState.IsValid) {
//do something with model
}
}
I can get the model value just fine but Request.Files always returns null. I also tried using HttpPostedFileBase but it also always return null
[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]
public void Register(RegisterViewModel model, HttpPostedFileBase files)
{
//files always null
if (ModelState.IsValid) {
//do something with model
}
}
First you need to give you file control a name attribute so it can post back a value to your controller
<input type="file" name="files" /> //
Then serialize your form and the associated file(s)
var formdata = new FormData($('form').get(0));
and post back with
$.ajax({
url: '#Url.Action("Register", "Membership")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (data) {
....
}
});
Note also the file input needs to be inside the form tags
You need to use FormData with combination of contentType, processData setting to false:
var formData = new FormData();
formData.append("userfile", $('#frmRegister input[type="file"]')[0].files[0]);
// append the file in the form data
$.ajax({
type: 'POST',
url: '/Membership/Register',
data: formdata, // send it here
dataType: 'json',
contentType:false, // this
processData:false, // and this should be false in case of uploading files
headers: fnGetToken(),
beforeSend: function(xhr) {
},
success: function(data) {
//do something
},
error: function(xhr) {
}
})
<input type="file" id="LogoImage" name="image" />
<script>
var formData = new FormData($('#frmAddHotelMaster').get(0));
var file = document.getElementById("LogoImage").files[0];
formData.append("file", file);
$.ajax({
type: "POST",
url: '/HotelMaster/SaveHotel',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
swal({
title: "Good job!",
text: "Data Save successfully!",
type: "success"
});
$('#wrapper').empty();
$('#wrapper').append(htmlData);
},
error: function (error) {
alert("errror");
}
});
</script>
public ActionResult SaveHotel(HotelMasterModel viewModel, HttpPostedFileBase file)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
file.SaveAs(path);
}
return View();
}
I need some help. I write little app using ASP.NET MVC4 with JavaScript and Knockout and I can't send data from javascript to MVC Controller and conversely. For example, the part of JS looks like that:
JavaScript
self.Employer = ko.observable();
self.AboutEmployer = function (id) {
$.ajax({
Url.Action("GetEmployer", "Home")
cache: false,
type: 'GET',
data: "{id:" + id + "}",
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
self.Employer(data);
}
}).fail(
function () {
alert("Fail");
});
};
In ASP.NET MVC Home Controller I'm getting employer by ID and return it as Json:
C#
public JsonResult GetEmployer(int id)
{
var employer = unit.Repository<Employer>().GetByID(id);
return Json(employer, JsonRequestBehavior.AllowGet);
}
My View return another Controller (Home/KnockOutView). My View also gets another objects and depending what recieve, has different look:
HTML
...
<b>About Company: </b><a href="#" data-bind="click: $root.AboutEmployer.bind($data, Vacancy().EmployerID)">
<span data-bind=" text: Vacancy().Employer"></span></a>
<div data-bind="if: Vacancy">
<div id="VacancyDescription"><span data-bind="text:DescriptionShort"></span>
</div>
</div>
<div data-bind="if: Employer">
<div data-bind="text: Employer().EmployerDescription"></div>
</div>
Everything works great, I receive Vacancy and Employer objects in JS and show it in HTML using Knockout, but my URL all time still the same!!! But I want to change URL all time, when i'm getting Vacancy or Employer.
For example, if I want to get Employer, using method GetEmployer, URL should looks like that: ~/Home/GetEmployer?id=3
If I change this string of Code
Url.Action("GetEmployer", "Home") at url: window.location.href = "/home/GetEmployer?id=" + id URL will be changed, but Controller returns me an Json object and shows it in window in Json format.
Help me, please, to change URL and get information in Controller from URL.
Thanks.
Try below code, hope helps you
This code works %100 , please change below textbox according to your scenario
HTML
<input type="text" id="UserName" name="UserName" />
<input type="button" onclick="MyFunction()"value="Send" />
<div id="UpdateDiv"></div>
Javascript:
function MyFunction() {
var data= {
UserName: $('#UserName').val(),
};
$.ajax({
url: "/Home/GetEmployer",
type: "POST",
dataType: "json",
data: JSON.stringify(data),
success: function (mydata) {
$("#UpdateDiv").html(mydata);
history.pushState('', 'New URL: '+href, href); // This Code lets you to change url howyouwant
});
return false;
}
}
Controller:
public JsonResult GetEmployer(string UserName)
{
var employer = unit.Repository<Employer>().GetByID(id);
return Json(employer, JsonRequestBehavior.AllowGet);
}
Here is my controller action.
[HttpPost]
public ActionResult ActionName(string x, string y)
{
//do whatever
//return sth :)
}
and my post action is here.
<script type="text/javascript">
function BayiyeCariEkle(){
var sth= $(#itemID).text();
var sth2= $(#itemID2).text();
$.post("/ControllerName/ActionName", { x: sth, y: sth2});
}
</script>
use data parameters like this {id:id, otherPara:otherParaValue}
$.ajax({
url:Url.Action("GetEmployer", "Home")
type: 'GET',
data: {id:id},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
alert(data)
}
});
Due to MVC being slightly annoying in it's processing of routes to the same view, I've had success doing this:
self.Employer = ko.observable();
self.AboutEmployer = function (id) {
$.ajax({
url: "#Url.Action("GetEmployer", "Home", new { id = "PLACEHOLDER"})".replace("PLACEHOLDER", id),
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
self.Employer(data);
}
}).fail(
function () {
alert("Fail");
});
};
You can use standard url: "#Url.Action("GetEmployer", "Home")/" + id, but on refresh, the route with the existing ID stays in subsequent calls, so it begins appending the id, which obviously doesn't work. By specifying the ID in call, that behavior is no longer present.
The best way for navigation on my opinion, is to use sammy.js. Here is a post about that kazimanzurrashid.com