Passing form data to a controller method using Ajax - c#

Experts,
I have form data -
var formdata = JSON.stringify($('#emailrequest').serializeArray());
and a url -
var urlofRequest = window.location.href; //This url is of above Emailrequest form .
My question is -
How do we send these two - formdata and urlofRequest to a .cs(controller) method -
public JsonResult ProcessEmailrequest()
{
// What code and parameters?
}
The controller method which opens up the form is -
public ActionResult EmailRequest()
{
return View();
}
I have the below code but it does not seems to work -
$.ajax({
url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
type: 'GET',
data: formdata,
sucess: function (data) {
alert('DataPosted');
}
})

The type in the ajax call is GET; no data is being posted to the form. Try making it a post or put. example jquery ajax post Also keep in mind that you are posting form data, so you will need to have parameters on the post method ProcessEmailrequest on the supply-chain-pressure controller to catch the data. example of mvc post method This is a jquery/ajax example that does basically the same thing jquery/ajax example

Related

How to pass jQuery variable value to c# mvc?

How to pass jQuery variable value to c# mvc ?
I need to fetch the value of the variable btn in mvc code behind.
$('button').click(function () {
var btn = $(this).attr('id');
alert(btn);
$.ajax({
type: 'GET',
url: '#Url.Action("ActionName", "ControllerName")',
data: { id: btn },
success: function (result) {
// do something
}
});
});
Based on the variable value (Submit Button (or) Preview Button), my model will have Required validation on certain fields.
In my controller , i am calling as
[HttpGet]
public ActionResult ActionName(string id)
{
var vm = id;
return View(vm);
}
Though , ActionResult in controller is not invoked.
Jquery : alert(btn); -- is calling. I can see the alert window showing with the id. However, I am not able to retrieve the id in the controller.
You need to use jQuery.ajax() (or its shortened form jQuery.get()/jQuery.post()) with GET/POST method and set up a controller action with an argument to pass button ID:
jQuery (inside $(document).ready())
$('button').click(function () {
var btn = $(this).attr('id');
var url = '#Url.Action("ActionName", "ControllerName")';
var data = { id: btn };
// if controller method marked as POST, you need to use '$.post()'
$.get(url, data, function (result) {
// do something
if (result.status == "success") {
window.location = '#Url.Action("AnotherAction", "AnotherController")';
}
});
});
Controller action
[HttpGet]
public ActionResult ActionName(string id)
{
// do something
return Json(new { status = "success", buttonID = id }, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult AnotherAction()
{
// do something
return View(model);
}
If you want to pass retrieved button ID from AJAX into other action method, you can utilize TempData or Session to do that.
It is a nice coincidence that you use the word "fetch" to describe what you want to do.
jQuery runs in the browser as a frontend framework. Meaning that it runs on the client`s computer. Your MVC-C#-Code lies on the server. Therefore, if you want to send data between those two computers, you need to use the http protocol.
1. Ajax and REST:
Using an ajax call using http methods (post or put) to push your variable value as JSON to the backend`s REST api (route).
For this option, you might want to have a look at the fetch function of javascript.
2. HTML Forms
Use a html form where you store the variable value inside one input element. A form submission will perform a http post (by default) request to the backend as well and use all input element values as post parameters.
There are many ways to accomplish what you are looking to do, but I'll stick to using your code sample.
So what you need to do is utilize the .ajax call in jquery to send data from your view to your controller. More on that here: http://api.jquery.com/jquery.ajax/
Using your code, you'd put the .ajax call within your logic flow of what to do based on which button is clicked.
$("button").click(function ()
{
var btn = this.id;
if (btn == "previewButton")
{
$.ajax({
url: "/MyApp/MyAction",
type: "POST",
data: { btnId: btn },
dataType: "json",
async: true,
cache: false
}).success(function(data){
// do something here to validate if your handling worked
}).error(function(){
// Do something here if it doesnt work
});
}
}
You'll see that there is a URL. In my example i've chose MyApp as my controller and MyAction as the method of the controller in which we are posting values to. The ajax call posts 1 parameter with a property of btnId. If you need to pass more data, the property name in the jquery call should correspond with an argument of the actions method signature within the controller.
So my controller looks like
public MyAppController : Controller
{
[HttpPost]
public JsonResult MyAction(string btnId)
{
Debug.WriteLine("btnId: {0}", btnId);
return Json(new{ ButtonId= btnId });
}
}
This would be one way to handle passing values from your view to your controller using .ajax calls with jquery.
My preferred way is to use the Html helpers of Ajax.BeginForm which could be another option for you.
https://www.aspsnippets.com/Articles/ASPNet-MVC-AjaxBeginForm-Tutorial-with-example.aspx

Return view after ajax post to controller

I'm sending some json data with ajax by post
function SendF() {
$.ajax({
url: '#Url.Action("Summary")',
type: 'POST',
data: JSON.stringify(flags),
contentType: "application/json;charset=utf-8",
success: function() {
},
error: function() {
alert("Oops! We've experienced a connection problem!");
}
});
}
to my controller
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
[...]
return View(flags);
}
and tried returning a view with data I've processed, but I guess it's not gonna happen since ajax is all about asynchronous http requests. How do I change my code to be synchronous?
The whole idea behind using ajax is to give the user the partial page update experience. If you are making an ajax call and once that is done and you are doing a redirect to another page, it does not give the partial page update experience to user. It looks very similar to the normal form submit(full page submit).
If you absolutely have to send the data to server via ajax , but want to do the redirect after the ajax call is successfully finished, you can do that using javascript in the success or done callback event on the $.ajax method.
All you have to do is, set the location.href property to the new url.
var flags = ["aa", "bb", "cc"];
$.ajax({
url: '#Url.Action("Summary")',
type: 'POST',
data: JSON.stringify(flags),
contentType: "application/json;charset=utf-8"
}).done(function(res) {
window.location.href = res.newUrl;
}).fail(function(xhr, a, error) {
console.log(error);
});
This assumes that your server action method returns a JSON response with the newUrl property which contains the url you want to redirect to .
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
return Json(new { newUrl = Url.Action("Index","Home") });
}
One way to do this would be to send the request to the controller via ajax and then render a partial view on your page. The easiest way would be to use the built in ajax helpers in ASP MVC. Here is a link to another post that gives a pretty good overview:
How to render partial view in MVC5 via ajax call to a controller and return HTML

Cant pass data from angular to Mvc controller

Its is my Angular controller
var app=angular.module('app',[]);
app.controller('myCtrl', function ($scope,$http) {
console.log($scope.add)
$scope.asd = function (data)
{
$http({
url: '/Home/My',
method: "GET",
data: data
});
}
//console.log($scope.asd);
});
When im passing data like this it is working well
{
$http({
url: '/Home/My',
method: "GET",
params: { data: data}
});
}
Mvc controller
public ActionResult My(List<string> data)
{
return View();
}
But why couldnt i pass it with "data"?
Looking at the Angular documentation at https://docs.angularjs.org/api/ng/service/$http , it seems that the "params" parameter refers to data that you want to pass as HTTP GET parameters, while the "data" parameter simply dumps the content into the HTTP request.
Is there a specific reason why you want it to work the first way? If there is not, then the second way appears to be the more elegant choice as it strengthens the interface contract between your Angular and MVC components.

How to refresh my Partial View after Ajax Post in MVC?

So basically I'm trying to show some Profile Data in my MVC Application.
Right now, everytime I click on a date on my Telerik Kendo Calendar, I can refresh the whole page and update the data I want.
However, instead of refreshing the whole I just want to refresh the partial views that shows only the data that updates after selecting the date.
Index.cshtml
<!--CODE-->
#Html.Partial("_WorkingTimeData")
<!--CODE-->
_WorkingTimeData.cshtml
var workedTime = ViewData["WorkedTimeToday"];
var hoursPerDay = ViewData["HoursPerDayContract"];
<p>You worked #workedTime hours</p>
<p>Hours Per Day (Contract) #hoursPerDay Hours</p>
Yes, right now I'm ViewDatas and it works.
This is the ajax code in Index.cshtml
$.ajax({ url: '/Profile/Index',
dataType: "json",
type: "POST",
data: JSON.stringify(10),
success: function(returl){
alert('It worked');
location.href=returl.Url;
},
error: function(jqXHR,responseText,textStatus){ alert(jqXHR.responseText) } });
Controller
[HttpPost]
public ActionResult Index(string number){
//THINGS TO DO
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile");
return Json(new { Url = redirectUrl });
}
Well I'm very new to this, and I've been doing my research. However I still have some questions:
- Do I need to create a post method for _WorkingTimeData instead of Index like I have?
- Do I need to create a ViewModel for the Partial View?
Thanks
EDIT NUMBER 2 FOR VISHAL:
This didn't work at all, not even an alert, because, strangely, it doesn't recognise the calendar...
$("#calendar").kendoCalendar({
change : function() {
$.ajax({
url: "/Profile/WorkingTimeData",
type: "get"
}).done(function(data) {
$("#profile-timeline").html(data);
});
}});
It says $("#calendar").kendoCalendar is not a function (Telerik says that it's this way)
As for this, it reached the controller but didn't update anything:
function change() {
alert("Escolheste outro dia");
var calendar = $("#calendar").data("kendoCalendar");
var current = calendar.current();
alert(current);
$.ajax({
url: "/Profile/WorkingTimeData",
type: "get"
}).done(function(data) {
$("#profile-timeline").html(data);
});
}
I think it's because of the profile-timeline... It's a div in my view
Do I need to create a post method for _WorkingTimeData?
Yes, you need to create. But, Get would be fine too.
Do I need to create a ViewModel for the Partial View?
Not needed. If required you can create.
But, by looking at your partial view you are just using ViewData[""]. So, you need not to create any ViewModel.
Just create a method in Controller returning _WorkingTimeData PartialView.
And call that method by JQuery ajax on your DatePicker change event and replace the contents of the Div.
For example.
Controller
public PartialViewResult WorkingTimeData()
{
ViewData["WorkedTimeToday"]="NEW VALUE";
ViewData["HoursPerDayContract"] = "NEW VALUE";
return this.PartialView("_WorkingTimeData");
}
JavaScript
$("DATEPICKERELEMENT").change(function() {
$.ajax({
url: "/CONTROLLER/WorkingTimeData",
type: "get"
}).done(function(data) {
alert(data);
$("#divisionIdContainingPartialView").html(data);
}).fail(function() {
alert('error');
});
});
I wrote a post that details why you need to break the logic of thinking about partial views client-side. If you're interested you can find it here.
The TL;DR version is simply, all you have client-side is HTML. There's no knowledge about what was or was not rendered to the response via a partial view. As a result, the real question is "How do I change a portion of my HTML page based on an AJAX response?". In the simplest form, you simply select some element on the page and then alter its inner HTML. You can do that with some custom HTML created client-side or you can actually pass back an HTML document as your AJAX response and then insert that.

Call a class in javascript in visual studio

I have a controller class that I get data from database and return it in a function, Now I want to call this function in a js and set the data in variables to show in a page:
My code looks like: exampleController.cs
namespace iSee.WebApiHse.Controllers
{
public class expController : StandardController
{
public expController(
first myService,
ISystemSettings systemSettings,
IService myExpService)
{
_myService = MyService;
_systemSettings = systemSettings;
_myExpService = myExpService;
}
// GET data
public ActionResult Myexample(int id)
{
var elementIds = _systemSettings.ExpIds;
var myElements = CacheService.AllVisibleElements
.Where(x => elementIds.Contains(x.Id)).ToList();
var container = _kpiContainerService.Find(id);
var result = _myService.MonthByContainer(myElements, container);
return AsJson(result);
}
}
}
This works and I get the data. Now I have myExp.js that I need to use these data in it. How can I do that?
Thanks
You need to execute $ajax(..) (jquery syntax) request to your controller to pass and get compute information from the server.
For this your controller method, that you're going to call, has to be exposed for HTTP access.
More details on :
How to call controller method from javascript
Do you want work with your controller in View by JavaScript? It isn't good idea. You should pass Model to View and work with it or ajax and recieve json-data
An example that uses jQuery-ajax to call your C# method:
// javascript
var id = 987;
$.ajax({
url : '/expController/Myexample/',
type : 'GET',
data { id : id },
dataType : 'json', // <-- tell jQuery to decode the JSON automatically
success : function(response){
console.log(response);
}
});
This would call your method, passing in the value of id, then it would decode the JSON into the response object.
For plain Javascript ajax (no jQuery) see MDN Ajax.
You need to make a request to the Action Myexample. Usually this is done via AJAX:
In your view you could have:
function makeAJaxCall(idToSend) {
$.ajax({
url: '#Url.Action("exp", "Myexample")',
data: { id : idToSend },
type: "POST",
success: function(data) {
$("#HTMLElement").val(data.YourData);
}
});
}
Your response will come back in the data variable if the AJAX call succeeds. I have provided an example to show you how to change the value of an HTML element with the ID HTMLElement.
To invoke the function you can do:
makeAjaxCall(100);
You may load the JSON data in a var and pass it to the function in expjs.js, as:
var data = data_from_ajax();
exp_js_function(data);
data_from_ajax() would receive JSON data from your controller and action method.
Please consider this as a starting point and not as a copy-paste solution

Categories

Resources