Passing the json object to a Asp.net mvc Controller - knockout-mvc

I want to pass a json object to a Controller through Ajax post method in a Asp.net MVC project.But Ajax post method fails to send the json object to the controller.How can i pass the json oject properly to the controller using Ajax post method?

var data = new Object();
data.Name = "Bla";
data.Surname="Bla";//This is our view model
$.post("/api/controller/action",data,function(result){alert(result);},"json");
The wep api controller or controller
[HttpPost]
public IHttpActionResult ActionName(MyViewModel model)
{
return Ok("yuppiiii");
}

Related

Generating link using urlhelper in MVC 6 controller (vNext)

I am trying to learn the new MVC 6. I never used the Microsoft MVC framework before.
I am trying to enhance an simple tutorial web API by adding links to different actions of my controllers using the URL (urlhelper) of the controller (Home controller showing what the API can do).
But when I use:
this.Url.Action("Get", new {id = id});
I get a query string with the URL. I'd like a more restful-style URL.
I thought when using the attributes routing, I do not have to map a specific route like I see in old tutorials of WebApi.
Do I have to map a route ?
What do I have to do to get a more restful URL style ?
You can add a name to the route attributes in your controller, then use the extension method IUrlHelper.RouteUrl to generate the url.
For example, given the following web api controller:
[Route("api/[controller]")]
public class UsersController : Controller
{
// GET: api/users
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/users/5
[HttpGet("{id}", Name ="UsersGet")]
public string Get(int id)
{
return "value";
}
//additional methods...
}
You can generate the url api/users/123 for the specific get by id action using #Url.RouteUrl("UsersGet", new { id = 123 }).
The problem when using the Url.Action extension method is that if you have a controller like in the example above with 2 actions named "Get", this will use the route for the action without parameters and generate /api/Users?id=123. However if you comment that method, you will see that #Url.Action("Get", "Users", new { id = 123 }) also gives you the expected url.

How to return related entities when inserting/posting a new one using OData Web Api

I've created an OData v4 endpoint using ASP.NET Web API 2.2 and wondering how to return related entities when inserting/posting a new one?
Controller:
public async Task<IHttpActionResult> Post(LibraryFolder libraryFolder)
{
this.db.LibraryFolders.Add(libraryFolder);
//Add MediaFiles to the conext
this.businessController.RefreshLibrary(libraryFolder);
await this.db.SaveChangesAsync();
//The libraryFolder object contains the MediaFiles at this point, but they get stripped out when going back to the client
return this.Created(libraryFolder);
}
Simply to add [EnableQuery] on the Post action. For example:
[EnableQuery]
public async Task<IHttpActionResult> Post(LibraryFolder libraryFolder)
{
...
}
Now, send the Post request to the Uri with $expand clause. For example:
POST http://..../odata/LibraryFolders?$expand=XXXX
Content-Type: application/json
Content: {...}

MVC Model Binding with Attribute Routing

Converting an MVC 3 app to MVC 5 and relying exclusively on Attribute Routing. All is good but I am unable to define a route for a controller method that accepts a (not so) complex object as a parameter.
If I omit the parameter in the route, my controller/method is never invoked and I receive a 404 (as I would expect). When I include the viewModel parameter as part of the route, my method is invoked but the parameter is always null.
This code worked fined before with "classic" routing and no specific route was needed to model bind my viewModel parameter. I never defined it as part of any route other than including the controller and method names. The view is unchanged.
[RoutePrefix("Text")]
[Route("{action}")]
public class TextController : Controller
{
[HttpGet]
[Route("{jobTextID}")]
public ViewResult Edit(Guid jobTextID)
{
// this (get) works fine
}
[HttpPost]
[Route("{viewModel}"]
public RedirectToRouteResult Edit(TextEditViewModel viewModel)
{
// viewModel is always null
}
}
I think you should add the id to the POST action:
[HttpPost]
[Route("{jobTextID}")]
public RedirectToRouteResult Edit(Guid jobTextID, TextEditViewModel viewModel) { }
The resource is identified by the URL, not by a parameter in the body of the request. Use jobTextID to retrieve the entity from the database and ignore the id from the viewModel.

Jersey : How to send /pass Custom DTO to a Service class in Jersey

I am using Jersey Framework for developing my Webservices. I have a DTO object named UserInfo with setters and getters inside it. I am setting this DTO value initially when the user logs in. How can I pass this user-specific DTO to a Jersey service class?
I have tried setting them inside MultivaluedMap and Form but I was out of luck making it work.
This is my code :
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("queryTerm", "userdto");
Form f = new Form();
f.add("name", "1001D");
And this is the way I am trying to retrieve the Data.
public class HaiService {
#GET
#Produces("application/json")
#Consumes("application/json")
public String sayPlainTextHello(#Context UriInfo ui) {
MultivaluedMap queryParams=ui.getQueryParameters();
Iterator it=queryParams.keySet().iterator();
String theKey=null;
String returnString="";
while(it.hasNext()) {
theKey=(String)it.next();
System.out.println(queryParams.getFirst(theKey));
}
System.out.println("I am called");
return "Hi";
}
But I was out of luck. Typically my requirement is to store user-specific data on logon, and then retrive that inside the service class.
I am avoiding storing data in session because a user might login with multiple ID's under one browser, which produces the same session id, and there is a chance of data being overwritten for the first logged in user.

Facebook c# sdk mvc3 canvas issue with CanvasAuthorize

I'm creating a mvc3 canvas app using facebook c# sdk
The method name is create.
I also do a post and have another create method with [HttpPost] attribute.
When I add the [CanvasAuthorize(Permissions = ExtendedPermissions)] attribute to both the create methods, and a link from another page calls this create method, normally the get method should get called but in this case the post method gets called
But if I comment the post method then it goes to the get method.
Any ideas how to solve this.
Thanks
Arnab
This is because of the canvas authorization posting the access token into the page. The only way around it I've found is to create a different action that deals the post and use that action inside the view as post target. It will look something like this:
// /MyController/MyAction
// Post and Get
[CanvasAuthorize(Permissions = ExtendedPermissions]
public ActionResult MyAction(MyModel data)
{
MyModel modelData = data;
if(data==null)
{
modelData = new MyModel();
}
else
{
modelData = data;
}
return View(modelData);
}
// /MyController/MyActionPost
// POST only
[HttpPost]
[CanvasAuthorize(Permissions = ExtendedPermissions]
public ActionResult MyActionPost(MyModel data)
{
if(Model.IsValid)
{
//Processing code with a redirect at the end (most likely)
}
else
{
return View("MyAction", data);
}
}
Then in your MyAction view:
#using (Html.BeginForm("MyActionPost", "MyController"))
{
<!-- Form items go here-->
<inpuy type="submit" value="Submit" />
#Html.FacebookSignedRequest()
}
I have the same issue. It was doing a GET before, then suddenly when browse to an action with [CanvasAuthorize(Permissions = ExtendedPermissions)] attribute, it's doing a POST instead of a GET.