Ajax Post in MVC... Why is the string null? - c#

So basically I'm creating a Request system in a MVC application. I have this "Create Request" section where I can select the type of request I want to do in a DropDownList from Telerik. What I want to do is, every time I choose something from the list, a partial view appears with the form related to that type of request.
This is my ajax Post from the Create.cshtml View:
<script>
function change() {
var value = $("#RequestType").val();
alert(value);
$.ajax({
url: "/Request/CreateRequestForm",
type: "get",
data: { requestValue : JSON.stringify(value)}
}).done(function (data) {
$("#partialplaceholder").html(data);
}).fail(function () {
alert('error');
})
};
</script>
This is my controller:
public ActionResult Index()
{
//Things
return View();
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpGet]
public PartialViewResult CreateRequestForm(string dropDownValue)
{ string partialView="";
int RequestType = Convert.ToInt32(dropDownValue);
switch (RequestType)
{
case 1 :
partialView+="_CreateAbsence";
break;
case 2 :
partialView += "_CreateAdditionalHours";
break;
case 3 :
partialView += "_CreateCompensationDay";
break;
case 4 :
partialView += "_CreateErrorCorrection";
break;
case 5 :
partialView += "_CreateVacation";
break;
}
return this.PartialView(partialView);
}
Everytime time the even triggers my dropDownValue string is null... Why? Thanks in advance! :)
EDIT
View Code
<h1>Create New Request</h1>
#(Html.Kendo().DropDownList()
.Name("RequestType")
.DataTextField("Text")
.DataValueField("Value")
.Events(e => e.Change("change"))
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Absence",
Value = "1"
},
new SelectListItem() {
Text = "Additional Hours",
Value = "2"
},
new SelectListItem() {
Text = "Compensation Day",
Value = "3"
},
new SelectListItem() {
Text = "Error Correction",
Value = "4"
},
new SelectListItem() {
Text = "Vacation",
Value = "5"
}
})
.Value("1")
)
<script>
function change() {
var value = $("#RequestType").val();
alert(value);
$.ajax({
url: "/Request/CreateRequestForm",
type: "get",
data: { requestValue : JSON.stringify(value)}
}).done(function (data) {
$("#partialplaceholder").html(data);
}).fail(function () {
alert('error');
})
};
</script>
<div id="partialplaceholder">
</div>

First of all: The title says you're doing a post request but in your code there's a get request.
Second: In order to make it work you have to change either the name of the data in the javascript you're sending to match the parameter name in the c# code like:
<script>
function change() {
var value = $("#RequestType").val();
alert(value);
$.ajax({
url: "/Request/CreateRequestForm",
type: "get",
data: { dropDownValue: JSON.stringify(value)}
}).done(function (data) {
$("#partialplaceholder").html(data);
}).fail(function () {
alert('error');
})
};
</script>
or change the name of the parameter in the c# method, like:
[HttpGet]
public PartialViewResult CreateRequestForm(string requestValue )
{
...
}
Third: I'm quite sure you don't need to JSON.Stringify() the data. For more details about the Stringify() method & usages please check this link

Related

Making a post request and after submitting a form

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>

MVC Droplist to trigger controller to get data to populate another droplist

We were able to do this with Angular, but are trying to do this with MVC using C# and Razor and possibly jQuery if need be.
What we are trying to do is, we populate a dropdown list with data already populated. (done). In our View we put an onChange event in which we then want to trigger another method in the controller so that we may get another list of items to populate the next droplist.
IN doing some VERY simple examples,we keep either getting a 404 or 500 return in our browser console and not hitting any breakpoints in Visual Studio.
This is what I have so far:
View
<div> #Html.DropDownListFor(model => model.Name, Model.AvailableGalaxyEventTypes, new { #id = "eventTypeName", onchange = "GetEventNames();" })
</div>
<script>
function GetEventNames() {
var url = '#Url.Action("GetData")';
var strId = 0;
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { value: strId },
success: function (result) {
alert(result);
console.log(result);
$('#result').html(result);
}
});
}
</script>
Controller
public ActionResult GetData(string id)
{
return Json(new { foo = "bar", ball = "dragon" });
}
I don't understand why we are not getting a success or anything back doing this very simple example. I should get Foo and Ball back. If we could get to the controller method, we should be able to make headway but I am getting 404 or 500 now.
Any ideas?
your method is accepting parameter id but you are passing value as parameter in ajax request
data: { id: strId }
or try by specifying controller name as well as action method name explicitly
url: '#Url.Action("Foo", "SomeController")',
#Html.DropDownListFor(model => model.CountryId, Model.AvailableCountries)
#Html.DropDownListFor(model => model.RegionId, Model.AvailableRegions)
$("##Html.FieldIdFor(model => model.CountryId)").change(function () {
var selectedItem = $(this).val();
var ddlRegions = $("##Html.FieldIdFor(model => model.RegionId)");
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetRegionsByCountryId"))",
data: { "countryId": selectedItem, "addSelectStateItem": "true" },
success: function (data) {
ddlRegions.html('');
$.each(data, function (id, option) {
ddlRegions.append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve regions.');
}
});
And extension method that gets Id of DDL (or you can do it using JQuery or Vanilla JS):
public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
// because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
return id.Replace('[', '_').Replace(']', '_');
}
And method in controller:
public ActionResult GetRegionsByCountryId(string countryId)
{
var country = _countryService.GetCountryById(Convert.ToInt32(countryId));
var states = _stateProvinceService.GetStateProvinces(country != null ? country.Id : 0).ToList();
var result = (from s in states
select new {id = s.Id, name = s.Title})
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}

reading ajax request body values by name with asp.net mvc 5 action controller

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

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