Do i have to list all controller functions? - asp.net-mvc-3

Do i have to list all controller functions in Global.asax.cs file?
Im creating a api for my workout and have created the controller WorkoutController. It has the action AddWorkout that takes some parameters, for instance username, password, duration and type. Two first are string, two last is ints.
Now, do i need to create a route for it? And every action with different action signature? Why could it not fall in under the default route? Calling it would break if i dont supply the correct variables, but i know what im doing :D
routes.MapRoute(
"AddWorkout", // Route name
"Workout/AddWorkout/", // URL with parameters
new { controller = "Workout", action = "AddWorkout" } // Parameter defaults
);
??? :D ???

You can easily create a REST Api:
routes.MapRoute(
"Workout", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
and use for example of your Workout:
public class WorkoutController : Controller
{
public ActionResult Index()
{
return RedirectToAction("Index", "Help");
}
[HttpPost]
public ActionResult Workout(FormCollection form)
{
// HTTP POST: ADD Workout
// process form and return JSON
return Json(myObject);
}
[HttpDelete]
public ActionResult Workout(string id)
{
// HTTP DELETE: REMOVE Workout
// process form and return JSON
return Json(myObject);
}
[HttpGet]
public ActionResult Workout(string id)
{
// HTTP GET: GET Workout
// process form and return JSON
return Json(myObject);
}
}
But I would suggest you to use WCF though :)
From a client side:
$.ajax({
type: "POST",
url: "/Workout/Workout",
data: {
'type': '123456',
'height': '171'
}
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$.ajax({
type: "DELETE",
url: "/Workout/Workout",
data: { 'id': '123456' }
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$.get("/Workout/Workout", { 'id': '123456' }, function(msg){
alert( "Data Saved: " + msg );
});
remember to create a Login method that you would send a token that is required in all actions, so you know that the user manipulating your data is real.

Read this.
The "Url" property on the Route class defines the Url matching rule
that should be used to evaluate if a route rule applies to a
particular incoming request.

No, you don't have to do this at all. The default route looks at what methods are defined and will figure out what to call as long as your parameters line up to some method on the controller.

Related

Passing a boolean value to asp.net api controller via Ajax

I am trying to pass a single boolean value via ajax to a server API.
The API action is hitted but the parameter (shuffled) is false, though I am setting it to true via Ajax.
The api controller action is this:
[HttpPost("PostShuffled")]
public IActionResult PostShuffled([FromBody]bool shuffled)
{
userSession.Shuffled = shuffled;
return Ok();
}
My Ajax call is this:
function ChangeViewMode(el) {
if (el.id == "ViewShuffled") {
$.ajax({
url: "/api/Data/PostShuffled",
contentType: "application/json",
method: "POST",
data: JSON.stringify({ shuffled: true }),
success: function () { alert("ok"); }
});
}
}
My question is what am I doing wrong?
Ok I have solved the problem this way:
Defined a new class:
public class AjaxShuffled
{
public bool shuffled { get; set; }
}
Then in my controller changed:
[HttpPost("PostShuffled")]
public IActionResult PostShuffled([FromBody]AjaxShuffled s)
{
userSession.Shuffled = s.shuffled;
return Ok();
}
And now the value is passed correctly. I had to encapsulate the boolean into a class to make it work.
The problem is that shuffled is wrapped in an object instead of sent by itself. If you only want to send a boolean value, just send true or false itself: data: true or data: JSON.stringify(true) depending on how you've configured your web service to handle input formats for boolean. On the server side you should only need the [FromBody] descriptor on the API method parameter.

Using AJAX with MVC 5 and Umbraco

I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.
FYI, I am using MVC 5 and Umbraco 7.
I currently have the ajax code within the partial view (will want to move this to a js file at some point).
Here is the ajax code:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '#Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
Here is the Controller:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
The above code gives me a 404 Not Found Error:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
If I use:
url: '#Url.Action("GetTimeDifference", "TimeDifference")'
The #Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.
I have also tried:
#Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url is still Null.
I have added entries in to the Global.asax.cs for routing i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This doesn't seem to do anything.
I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.
As I am new to this I'm sure it something very simple I am missing.
Many thanks,
HH
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.
Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.

How to use ajax in asp.net MVC

How can I return a class object from Ajax in asp.net MVC....???
Example:
Ajax call from html:
$.ajax({
type: 'POST',
url: '/Tutorial/Web/AlignmentRule/GetAlignmentDetails',
data: { alignmentRuleId: alignmentRuleId },
success:
function (data) {
alert(data.Id);
alert(data.alignmentData.Id);
$("#ruleName").val(data.alignmentData.Name);
$("#level").val(data.alignmentData.Id);
},
error:
function () {
alert("Server Error!!!!");
},
dataType: 'JSON',
async: false
});
and Action method in contorller is:
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData );
}
And I want to return a list of alignmentRule class objects also....
you can compose your return object as you want, for example, create a ViewModel as decorator to hold everything you want to pass, like:
var json = new JsonViewModel() {
alignmentData = alignmentData,
rules = yourRules
};
return Json(json);
The error is thrown because by default MVC framework does't allow you to respond to an HTTP GET request with a JSON (because of security reasons).
In order to make it work, when you retrurn Json in your action, you need to specify JsonRequestBehavior.AllowGet
[HttpPost]
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData, JsonRequestBehavior.AllowGet);
}
EDIT
Annotate your action with [HttpPost] attribute.
For further investigation on this topic check this article

Parameter to Web Service via Jquery Ajax Call

I am using revealing module pattern and knockout to bind a form. When data is entered in that form(registration), it needs to be posted back to MVC4 web method.
Here is the Jquery code
/*
Requires JQuery
Requires Knockout
*/
op.TestCall = function () {
// Private Area
var _tmpl = { load: "Loading", form: "RegisterForm"};
var
title = ko.observable(null)
template = ko.observable(_tmpl.load),
msg = ko.observable(),
postData = ko.observable(),
PostRegistration = function () {
console.log("Ajax Call Start");
var test = GetPostData();
$.ajax({
type: "POST",
url: obj.postURL, //Your URL here api/registration
data: GetPostData(),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8'
}).done(Success).fail(Failure);
console.log("Ajax Call End");
},
GetPostData = function () {
var postData = JSON.stringify({
dummyText1: dummyText1(),
dummyText2: dummyText2(),
});
return postData;
}
return {
// Public Area
title: title,
template: template,
dummyText1: dummyText1,
dummyText2: dummyText2
};
}();
The controller code is simple as per now
// POST api/registration
public void Post(string data)
{
///TODO
}
When i am trying to, capture the data (using simple console.log) and validate it in jslint.com, it's a valid Json.
I tried hardcoding the data as
data: "{data: '{\'name\':\'niall\'}'}",
But still i get as null, in my web method.
Added the tag [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] to my Post method in controlled, but still no fruitful result
Even tried JSON.Stringify data: JSON.stringify(data) but still i get null in my web-method.
I am not able to figure out the solution.
Similar issue was found # this link
http://forums.asp.net/t/1555940.aspx/1
even Passing parameter to WebMethod with jQuery Ajax
but didn't help me :(
MVC and WebApi uses the concept of Model Binding.
So the easiest solution is that you need to create a Model class which matches the structure of the sent Json data to accept the data on the server:
public void Post(MyModel model)
{
///TODO
}
public class MyModel
{
public string DummyText1 { get; set; }
public string DummyText1 { get; set; }
}
Note: The json and C# property names should match.
Only escaped double-quote characters are allowed, not single-quotes, so you just have to replace single quotes with double quotes:
data: "{data: '{\"name\":\"niall\"}'}"
Or if you want to use the stringify function you can use it this way:
data: "{data: '" + JSON.stringify(data) + "'}"

Returning data from server asp.net mvc action to Jquery Ajax request

I add a link dynamically to a page, and I want the "name" property to be a value that is sent back from server.
This is the code I have for adding a song to the server and then I dynamically append link to my song with a delete button, and I want that button to have a name equal to the songID evaluated on the server side.
$.ajax({
url: "/Home/AddSong",
type: "POST",
data: $("#AddTopTenFavForm").serialize(),
success: function () { ShowMsg("Song Added Successfully"), $(container).find('ul').append('<li><a class="topTenFavLinks" href="#" name="' + substr + '" >' + name + '</a> <span name= #item.SongId class="btnDeleteSong dontDoAnything">x</span></li>'); },
error: function () { ShowMsg("There was an error therefore song could not be added, please try again") }
});
here is my mvc action:
[HttpPost]
public ActionResult AddSong(HomeViewModel songModel)
{
var song = new Song();
song.GenreId = songModel.topTenFav.Rank;
song.Date = DateTime.Now;
song.UserName = User.Identity.Name;
song.Title = songModel.topTenFav.Title;
song.YoutubeLink = songModel.topTenFav.YoutubeLink;
repository.AddSong(song);
repository.Save();
return RedirectToAction("Index");
}
How would I solve this issue in a single ajax request?
You need to return your song ID from the action
[HttpPost]
public ActionResult AddSong(HomeViewModel songModel)
{
//code goes here
return this.Content(song.Id.ToString());
}
and in the javascript success callback you will receive data in arguments:
success: function (data) { /* use data here for anchor name */ },
Use JsonResult to return your Id, and append to your link.
Look at examples
http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/
http://geekswithblogs.net/michelotti/archive/2008/06/28/mvc-json---jsonresult-and-jquery.aspx

Resources