This is my Controller :
public JsonResult Success() { return Json(new { Success = true, Message = "Data Added Succefully" }); }
public JsonResult Error(string message) { return Json(new { Success = false, Message = message }); }
[HttpPost]
public JsonResult CreateAjax(TAUX taux)
{
if (ModelState.IsValid)
{
try
{
foreach (short i in taux.SelectItems)
{
taux.CAT_ID = i;
db.TAUX.Add(taux);
db.SaveChanges();
}
return Success();
}
catch (Exception err)
{
return Error(err.Message);
}
}
ViewBag.CAT_ID = new SelectList(db.CATEGORIE, "CAT_ID", "LIBELLE", taux.CAT_ID);
ViewBag.C_GARANT = new SelectList(db.GARANTIE, "C_GARANT", "LIB_ABREGE", taux.C_GARANT);
return Error("The server wasn't able to do something right now.");
}
This is My PartialView CreateAjax:
#model pfebs0.Models.TAUX
....
#using (Html.BeginForm("CreateAjax", "Taux", FormMethod.Post, new { id = "form" }))
{...}
And this is my View Index :
#model IEnumerable<pfebs0.Models.TAUX>
...
<script>
$.ajax({
url: "/",
method: "POST",
data: getMyData(),
success: function (json) {
if (json.Success) {
alert("Wow, everything was fine!");
} else {
alert(json.Message);
}
},
// This will be trigered whenever your ajax call fails (broken ISP link, etc).
error: function () {
alert("Something went wrong. Maybe the server is offline?");
}
});
</script>
...
#Html.ActionLink("Ajouter", "Create", "Taux",
new { id = "btnAdd", #class="btn btn-default"})
</p>
...
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$('#btnAdd').click(function () {
$('.modal-dialog').load(this.href, function () {
$('#modalDiv').modal({
backdrop: 'static',
keyboard: true
}, 'show');
});
return false;
});
});
....
</script> }
What I'm trying to do here is to show success alert after Insertionn but after Insertion I'm redirected to new Page Localhost/Taux/ajaxCreate where It show me this message {"Success":true,"Message":"Data Added Succefully"} instead of showing PopUp with success message in Index Page. What's wrong here ?
You should use
#using (Ajax.BeginForm(....))
{ }
with the appropiate parameters.
See How can I return a JSON result to a Ajax.BeginForm for details.
There might be some issues with the script as well.
What are you trying to do with:
<script>
$.ajax({
url: "/",
method: "POST",
data: getMyData(),
?
UPDATE
Ok, this should work:
1) use your original
#using (Html.BeginForm
2) put the ajax call in a function:
<script type="text/javascript">
function postData()
{
$.ajax({
url: '#Url.Action("CreateAjax", "Taux")',
method: "POST",
data: $('#form').serialize(),
....
}
3) change the type="submit" to type="button" at the submit button and add:
onclick="postData()"
attribute.
4) change ajax url:
url: '#Url.Action("CreateAjax", "Taux")',
5) add the change the getMyData function function
data: $('#form').serialize(),
Related
I am having this problem while working on an eshop I am building, I want to simply do a post request to a controller (that is not returning a view) while also submiting a form.. I do not know what is wrong with this code
<script>
$(document).ready(function () {
console.log("sad");
$("a[data-form-method='post']").click(function (event) {
event.preventDefault();
var element = $(this);
var action = element.attr("href");
element.closest("form").each(function () {
var form = $("#form1");
form.attr("action", action);
form.submit();
});
});
});
</script>
Here is the form
using (Html.BeginForm("SendEmailToAdmin", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.Hidden("receiver", $"{user.Email}");
Customer Support
}
Here is the controller
[HttpPost]
[Route("/Home/SendEmailToAdmin")]
//[NonAction]
public JsonResult SendEmailToAdmin()
{
........
(some code
if is true )
return Json(new { status = "Thank you very much admin for showing up. Don't forget to send us the email of your feedback on your way out" }, JsonRequestBehavior.AllowGet);
}
(or else)
return Json(new { status = "Something went wrong, please try again" }, JsonRequestBehavior.AllowGet);
I have tried also using a button with the id of submitDemo
$('body').on('click', function (e) {
e.preventDefault();
alert("Handler for .click() called.");
$.post("~/Home/SendEmailToAdmin");
});
and also
$("#form1").submit(function (event) {
event.preventDefault();
$.post('#Url.Action("SendEmailToAdmin", "Home",new { id = email })');
document.signupform.submit();
});
have also tried using a variable for the button and then with onclick method and so on...
const button = document.getElementById('submitDemo');
EDIT : I HAVE TRIED THIS
I fount it at last.. here it goes!
Jquery:
$(document).ready(function () {
$("#submitBtn").click(function (event) {
console.log("sad");
event.preventDefault();
$.ajax({
type: "POST",
url: "#Url.Action("SendEmailToAdmin", "Home")",
data: "#email",
success: function () {
console.log("Done")
$("#form1").submit();
}
});
});
});
html in view : I added the btn outside of the form
and this way the submit form happens and also the post request!
using (Html.BeginForm("AdminSupport", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.Hidden("receiver", $"{user.Email}");
#*<button id="submitbutton" #user.Email=>Customer Support</button>*#
}
<button id="submitBtn" #*data-form-method="post"*#>Customer Support</button>
i want to access jquery ajax post request body to get the value on my asp.net mvc 5 controller action.
knowing that i m passing __RequestVerificationToken with success.
<script>
$(document).ready(
function () {
$("#renamedashboard").click(function () {
swal({
title: "Titre Dashboard",
text: "Saisir le nouveau titre:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputType : "text"
},
function (inputValue)
{
if (inputValue === false)
return false;
if (inputValue === "")
{
swal.showInputError("You need to write something!");
return false
}
alert(inputValue);
var form = $('#__AjaxAntiForgeryForm');
//form.append('<input type="hidden" name="name" value=' + inputValue + ' />');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: ($(this).data('url')),// i tried to do ($(this).data('url'))+'?name='+inputValue but i got undefined id
type: "POST",
data: {
name: inputValue,
__RequestVerificationToken: token
},
success: SuccessCallback,
error: FailureCallback
});
});
function SuccessCallback(data) {
swal({
title: "Opération réussie",
type: "success"
}, function () {
NProgress.done();
location.reload();
});
}
function FailureCallback(data) {
swal("Good job!", "You clicked the button!", "error");
NProgress.done();
}
});});
here is my controller
[HttpPost]
[ValidateAntiForgeryToken]
// POST: Dashboard/Rename/5
public async Task<ActionResult> Rename(int id,[System.Web.Http.FromBody] string name)
{
Dashboard dashboard = await dbs.Dashboards.FindAsync(id);
//dashboard.Visible = true;
dashboard.TitreD = name.ToString();
dbs.Entry(dashboard).State = EntityState.Modified;
await dbs.SaveChangesAsync();
return Json(new { success = true });
}
i have a hidden form on my view
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" })){
#Html.AntiForgeryToken()
}
the body content is
name|test
__RequestVerificationToken|the token
Fixed my problém was that ($(this).data('url')) are not giving the correct url because it's not reffering to $("#renamedashboard") who has the correct url
<a id="renamedashboard" href="#" data-url=#Url.Action("Rename", "Dashboard",new {id=activedashboard.Idd}) >
i'm new with ajax and i'm trying to call a post action from an ajax method like that
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre")');
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
my post method goes with success but instead of redirectin me to the MaSelection View it return the first view where i call the method, so i tried to put a "Success" fragment in my ajax method and i puted a location replace by "Ma selection" view but i know that the view lose the id so it become null, how can i do it with Ajax,
here my post action for more details
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return View("MaSelectionOffre", selectionOffre);
}
use json as datatype;
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.href = msg.redirect;
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
also you need this ;
Convert object to JSON string in C#
If you want redirect page, after ajax call you should use
...
success: function (msg) {
window.location.href = '#Url.Action("MaSelectionOffre", "DemandeLocation")';
},
...
EDIT
If you want replace result, use something like following:
HTML
<div id="updateTargetId">
//table
//tr
//td
//your button that has cssClass buttonSelection
</div>
JS
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
$("#updateTargetId").html(msg);
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
CONTROLLER (return PartialView)
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return PartialView("MaSelectionOffre", selectionOffre);
}
i changed my action to a get action and in my button i just added window.location.replace with link and ID
<button type="button" class="buttonSelection" onclick="window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre?id="+item.Publication_ID)')"> <span class="ui-icon ui-icon-cart"></span> </button>
I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:
JavaScript:
$("#subnt").click(function (event) {
event.preventDefault();
var url = "/Home/Submit";
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
})
});
});
C#:
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Please check below working code -
I have used exactly your working code -
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Then I used following JQuery to hit the above action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response);
},
success: function (data) {
if (data.Success == true)
alert(data.SomeOtherData);
}
});
});
});
</script>
<input type="submit" value="click" id="click" />
And as the output I was able to get an alert as shown below -
Easiest thing to do is use the superior json.net
[HttpPost]
public string Submit()
{
var result = new { success = true, someOtherDate = "testing"};
var json = JsonConvert.SerializeObject(result);
return json;
}
Your code is ok bu you can add debugger.and open developer tools check your data .
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
debugger;
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
No, the other way around. How to retrieve the data from the form (json).
Here is what I am trying to do. I'm trying to pass the drop down selected value to my controller.
I have a drop down menu like this:
#Html.DropDownList("divs", null, "--Select--", new {id="divs", onchange="SelectedIndexChanged(this.value);" })
#section Scripts
{
<script>
function SelectedIndexChanged(divs) {
document.getElementById('divs').href =
'/Controllers/MyFunction?divs=' + divs;
}
</script>
}
in my controller, I am trying to get the value divs:
public MyFunction (string divs)
{
string type = Request.QueryString["divs"];
MessageBox.Show(type); //this is empty
}
Typing this from my head compiler so it might not be quite right but should get you closer.
#Html.DropDownList("divs", null, "--Select--", new { id="divs"})
#section Scripts
{
<script>
$(function() {
$("#divs").change(function() {
val selected = $(this).find(":selected").val();
$.ajax({
type: 'POST',
url: '#Url.Action("MyFunction", "Controller", new { divs = selected })',
dataType: 'json',
});
});
});
</script>
}
In your controller:
public ActionResult MyFunction (string divs)
{
...
}
I believe that this is what you're trying to do. It's not a complete solution, you have to work it out.
Note: I'm using jQuery for the javascript part.
Action:
public JsonResult MyFunction (string divs)
{
return Json(divs, JsonRequestBehavior.AllowGet);
}
View:
$(function() {
$("#divs").changed(function() {
$.ajax({
url: '/controllers/myfunction'
, cache: false
, type: 'GET'
, dataType: 'json'
, data: { divs = $(this).val() }
}).done(function (data) {
alert(data);
});
});
});
You can remove that javascript binding from the dropdown declaration.