How to get the data from json to MVC4 c#? - c#

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).

Related

Ajax Posting twice ASP NET CORE MVC

Controller
[HttpPost]
public IActionResult Index(string mainFin, string actNumber, int actTypeId)
{
int userId = Int16.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
Act act = new Act()
{
ActTypeId = actTypeId,
CreateDate = DateTime.Now,
ApproveDate = null,
UserId = userId,
StatusId = 1,
};
_unitOfWork.ActRepository.Add(act);
_notyf.Success("Arayış əlavə edilid !");
_unitOfWork.Complete();
return RedirectToAction("Marriage");
}
AJAX
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
},
error: function () {
console.log("------");
}
});
e.preventDefault();
$("#questForm1").submit();
});
});
Problem : When I click submit button data inserts twice to database (AJAX makes 2 request at same time )
If you want to submit the form via AJAX then you need to remove the last line of the click event handler.
$("#questForm1").submit();
This line is submitting the form and essentially negating the e.preventDefault() above.
You are submitting your data twice: at first using ajax and after that using using the form submit.
You have to remove one of them, I would guess the form submit.
Also, since ajax is called async, if you want to do something after ajax has been called and returned successfully, you have to put the code in success section.
So the code should look like:
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
e.preventDefault();
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
// do your thing here, once the ajax requst has returned successfully
},
error: function () {
console.log("------");
}
});
// NOTICE: form submit removed
});
});

ASP.NET MVC AJAX Call to Controller Not Returning any Data

I'm trying to call an ASP.NET MVC controller using an AJAX Call. Basically I want to return customer details based on the ID selected from a dropdownlist. On debugging, controller is being hit and returning data in JSON format however, on debugging javascript, it never gets to success, failure or error.
Here is the code I'm using:
View:
<script type="text/javascript">
$(document).ready(function () {
$("#CustomerId").select2({
placeholder: "Select a customer"
});
$("#CustomerId").change(function () {
var param = $("#CustomerId Option:Selected").val();
$.ajax({
type: 'GET',
data: { Id: param },
url: '/QuickInvoices/GetCustDetails',
success: {
function(response) {
if (response != null) {
alert("hello");
$('customer_CompanyName').val(response.CompanyName);
}
else {
alert("something went wrong!");
}
}
},
failure: function (response) {
alert('failed');
},
error: function (response) {
alert('error' + response.responseText);
}
});
});
});
</script>
Controller:
[HttpGet]
public JsonResult GetCustDetails(int Id)
{
Customer customer = db.Customers.Where(x => x.Id == Id)
.SingleOrDefault<Customer>();
return Json(customer, JsonRequestBehavior.AllowGet);
}
Can someone help please?
Please try below Code sample and check the Request & Response of network tab
you will get batter Idea
$(document).ready(function () {
$("#CustomerId").select2({
placeholder: "Select a customer"
});
$("#CustomerId").change(function () {
var param = $("#CustomerId Option:Selected").val();
$.ajax({
type: "POST",
url: '#Url.Action("GetCustDetails", "QuickInvoices")',
data: { Id: param },
dataType: "json"
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data.msg);
},
error: function() {
alert("Error occured!!")
}
});
});
});

How to make GET Ajax call to Asp.Net Core Mvc controller

I am new to MVC, and I am working on a homework project where I need to make ajax call to a controller so I can select data from the database. When I make the ajax call I get 200 HTTP code but the I can't print what's in the success: in the ajax parameters. If anyone knows the solution to this, please help me. Thank you in advance
MVC controller
[HttpGet]
public JsonResult GetPasos(string pasos)
{
var patnici = _context.Patnici
.FirstOrDefaultAsync(m => m.PassporNo == pasos);
return new JsonResult(patnici);
}
Ajax call:
$(document).ready(function () {
$("input#PassporNo").on("input", function () {
var input = document.getElementById("PassporNo").value;
var regex = new RegExp("^[A-Z0-9]+$");
if (regex.test(input) && input.length === 8) {
//$("input#PassporNo").on("input", function () {
console.log("blabla")
$.ajax({
//base address/controller/Action
url: '/Patnicis/GetPasos/',
type: 'GET',
data:
//Passing Input parameter
{"pasos": $('input#PassporNo').val() }
,
success: function (result) {
console.log("Rabote ajax");
},
error: function (jqXHR, textStatus, errorThrown, data) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
console.log(data)
}
});
return false;
}
});
});
Change your controller action attribute [GET] to [Route("~/Patnicis/GetPasos/{pasos}")]
And try this:
(document).ready(function () {
$("input#PassporNo").on("input", function () {
var input = document.getElementById("PassporNo").value;
var regex = new RegExp("^[A-Z0-9]+$")
if (regex.test(input) && input.length === 8) {
//$("input#PassporNo").on("input", function () {
alert("blabla")
$.ajax({
//base address/controller/Action
url: '/Patnicis/GetPasos/' + input,
type: 'POST',
data: null,
success: function (result) {
alert(JSON.Stringify(result));
},
error: function (jqXHR, textStatus, errorThrown, data) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
alert(data)
}
});
return false;
}
});
});
Solved
The ajax call stays the same, only the action type of the controller changes
[Route("~/Patnicis/GetPasos/{pasos}")]
public async Task<Patnici> GetPasos(string pasos)
{
var patnici =await _context.Patnici
.FirstOrDefaultAsync(m => m.PassporNo == pasos);
return patnici;
}

Redirect with Ajax POST

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>

Asp.net MVC JsonResult succes Message

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(),

Categories

Resources