passing json data of webapi method from controller to view - json

I have data in my apicontroller in following way-
public class OutletPOCController : ApiController
{
OutletPOCContext db = new OutletPOCContext();
[System.Web.Http.ActionName("GetTabText")]
public TabTextModel GetTabText(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new TabTextModel
{
HomeTab = outlet.BizHomeTabText,
AboutTab = outlet.BizAboutTabText,
TimingsTab = outlet.BizTimingsTabText,
};
}
And now i want to retrieve this data into my view. How shall i create view for this controller and pass the above data? What will be my action method? I am new to webapi and json. Any help is appreciable! Thanks in advance!

The API controller dosent really have views in the sense that you create a cshtml page that takes care of how you display your data. The purpose of the ApiController is simply to return data in the format that you want to consume it.
Basically the API exposes raw data to the web, you consume it in some way, and then display it..
I use something similar to this to load data dynamically into a web page.
Just a simple web api that returns data to the client.
public class APIController : ApiController
{
[HttpGet]
[HttpPost] // allow both post and get requests
public IEnumerable<String> GetData()
{
return new List<string>() { "test1", "test2" };
}
}
When you browse to the API method above it returns this xml data
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>test1</string>
<string>test2</string>
</ArrayOfstring>
Which I get using Jquery and do what I please with (http://api.jquery.com/jQuery.get/):
$.get("/api/GetData", function(data) {
alert("Data Loaded: " + data);
});
Examples of XML parsing with JS/Jquery:
http://tech.pro/tutorial/877/xml-parsing-with-jquery
http://www.kawa.net/works/js/jkl/parsexml-e.html
If you are simply looking to get data into a regular view and work with it there without going through javascript I wouldent use a webapi, but instead get the data in the controller and send it to the view for displaying (ASP MVC4 - Pass List to view via view model).
You can also check out the ViewBag container for passing random odd data to the view http://goo.gl/03JTR
On the off chance you really do want to render your data in a view, check this out: Web API - Rendering Razor view by default?

Related

How to make my Apex class return or "run" a JSON? using APEX REST

I am using the following code to generate a JSON for a Salesforce custom object called Resource Booking. How can I "run" the file (or call responseJSON) so that when I input the custom URL (in the first comment) it jumps to a page similar to this example web page? https://www.googleapis.com/customsearch/v1?json
Here is my code:
#RestResource(urlMapping='/demo/createTask/*') //endpoint definition > {Salesforce Base URL}/services/apexrest/demo/createTask/
global class ResourceBookingTransfer {
public List<Resource_Booking__c> resourceBookingList{get; set;}
public ResourceBookingTransfer(ApexPages.StandardController controller) {
//getResourceBookingList();
}
#HttpGet //HttpGet request
global static responseWrapper getResourceBookingList() {
responseWrapper responseJSON = new responseWrapper(); //responseWrapper object for API response
responseJSON.message = 'Hello World';
return responseJSON; //return the JSON response
//resourceBookingList = Database.query('SELECT Booking_ID__c, Booking_Name__c, Start_Date_Time__c, End_Date_Time__c, Resource__c FROM Resource_Booking__c');
}
//wrapper class for the response to an API request
global class responseWrapper {
global String message {get;set;} //message string
//constructor
global responseWrapper() {
this.message = '';
}
}
}
To just test it - it might be simplest to use https://workbench.developerforce.com. There's "REST explorer" menu in there. Your code should be available under resource similar to /services/apexrest/demo/createTask.
Why that url? Read https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_code_sample_basic.htm
Once you're happy with this manual testing - you can try to do it from outside workbench. Workbench logs you in to SF and passed header with valid session id in the background. If you want to call your service from another website or mobile app - you need to perform login call first, get the session id and then run your code. There are several OAuth flows you can use to do this depending in what your app needs, maybe start with this one: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_username_password_oauth_flow.htm

Compress on code json string and return to client

I have a ASP.NET MVC Controller C# and inside I have the following method:
public JsonResult PlayersData()
{
List<Player> players = new List<Player>();
// here some code to fill players list
// ...
return Json(players, JsonRequestBehavior.AllowGet);
}
I would like to send the Json compressed, I mean the List because the json is heavy about 12MB.
I don't want to enable IIS compression, I need to do it within the same code.
Any clue?

Returning JSON Errors from Asp.Net MVC 6 API

I'm trying out building a web API with MVC 6. But when one of my controller methods throws an error, the content of the response is a really nicely formatted HTML page that would be very informative were this an MVC app. But since this is an API, I'd rather have some JSON returned instead.
Note: My setup is super basic right now, just setting:
app.UseStaticFiles();
app.UseIdentity();
// Add MVC to the request pipeline.
app.UseMvc();
I want to set this up universally. Is there a "right/best" way to set this up in MVC 6 for an API?
Thanks...
One way to achieve your scenario is to write an ExceptionFilter and in that capture the necessary details and set the Result to be a JsonResult.
// Here I am creating an attribute so that you can use it on specific controllers/actions if you want to.
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var exception = context.Exception;
context.Result = new JsonResult(/*Your POCO type having necessary details*/)
{
StatusCode = (int)HttpStatusCode.InternalServerError
};
}
}
You can add this exception filter to be applicable to all controllers.
Example:
app.UseServices(services =>
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CustomExceptionFilterAttribute());
});
.....
}
Note that this solution does not cover all scenarios...for example, when an exception is thrown while writing the response by a formatter.

spring3mvcportlet populate JSON dojo select

I am new to Spring mvc3 portlet and dojo. I am trying to populate select dropdown with JSON data when jsp is loaded. I want to use dojo and give ajax call to controller and return JSON when jsp is loaded. Any tips will be helpful.
#Controller
#RequestMapping("/yourController")
public class YourController
{
#RequestMapping(value="/combo/{id}", method=ReqestNethod.GET)
public String getDropDownData(#ParamValue("id") long id)
{
List<Combo> combos = commonDao.getCombos(id);
String json = JsonUtil.toJson(combos); // or whichever way you use
return json;
}
}
Send requests from dojo to this url
<your-context-path>/yourController/combo/1
where 1 is your combo id.
I haven't checked the syntax here.. Wrote it blind. You might get compilation errors.
I get data in below format
How do I populate dojoType="xwt.widget.form.FilteringSelect"
{"ValuesDTO": {"items": [{},{"default": {"size": 5},"int": 10,"string": "Product1","string": "Product1 ","string": "product3","string": "product4","string": "product5"}]}}
I am sending dat in bean--->DTO--->List

Getting a Partial View's HTML from inside of the controller

I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool.
My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.
Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.
This is a solution that is working with ASP.Net MVC 1.0 (many that claim to work with beta 3 don't work with 1.0), doesn't suffer of the 'Server cannot set content type after HTTP headers have been sent' problem and can be called from within a controller (not only a view):
/// <summary>
/// Render a view into a string. It's a hack, it may fail badly.
/// </summary>
/// <param name="name">Name of the view, that is, its path.</param>
/// <param name="data">Data to pass to the view, a model or something like that.</param>
/// <returns>A string with the (HTML of) view.</returns>
public static string RenderPartialToString(string controlName, object viewData) {
ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };
viewPage.Url = GetBogusUrlHelper();
viewPage.ViewData = new ViewDataDictionary(viewData);
viewPage.Controls.Add(viewPage.LoadControl(controlName));
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb)) {
using (HtmlTextWriter tw = new HtmlTextWriter(sw)) {
viewPage.RenderControl(tw);
}
}
return sb.ToString();
}
public static UrlHelper GetBogusUrlHelper() {
var httpContext = HttpContext.Current;
if (httpContext == null) {
var request = new HttpRequest("/", Config.Url.ToString(), "");
var response = new HttpResponse(new StringWriter());
httpContext = new HttpContext(request, response);
}
var httpContextBase = new HttpContextWrapper(httpContext);
var routeData = new RouteData();
var requestContext = new RequestContext(httpContextBase, routeData);
return new UrlHelper(requestContext);
}
It's a static method you can drop somewhere you find it convenient. You can call it this way:
string view = RenderPartialToString("~/Views/Controller/AView.ascx", someModelObject);
I put together a rough framework which allows you to render views to a string from a controller method in MVC Beta. This should help solve this limitation for now.
Additionally, I also put together a Rails-like RJS javascript generating framework for MVC Beta.
Check it out at http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvc and let me know what you think.
You would create your action like this:
public PartialViewResult LoginForm()
{
var model = // get model data from somewhere
return PartialView(model);
}
And the action would return the rendered partial view to your jquery response.
Your jquery could look something like this:
$('#targetdiv').load('/MyController/LoginForm',function(){alert('complete!');});
You should use jquery to populate your divs (and create new html elements if needed), and Json serialization for ActionResult.
Other way is to use jquery to call some controller/action, but instead json use regular View (aspx or ascx, webforms view engine) for rendering content, and with jquery just inject that html to some div. This is half way to UpdatePanels from asp.net ajax...
I would probably go with first method, with json, where you have little more job to do, but it's much more "optimized", because you don't transfer whole html over the wire, there are just serialized objects. It's the way that "big ones" (gmail, g docs, hotmail,..) do it - lot of JS code that manipulates with UI.
If you don't need ajax, then you basically have two ways of calling partial views:
html.renderpartial("name of ascx")
html.RenderAction(x=>x.ActionName) from Microsoft.web.mvc (mvc futures)
After much digging in google i have found the answer.
You can not get easy access to the html outputted by the view.
http://ayende.com/Blog/archive/2008/11/11/another-asp.net-mvc-bug-rendering-views-to-different-output-source.aspx
I've done something similar for an app I'm working on. I have partial views returning rendered content can be called using their REST path or using:
<% Html.RenderAction("Action", "Controller"); %>
Then in my actual display HTML I have a DIV which is filled from jQuery:
<div class="onload">/controller/action</div>
The jQuery looks like this:
<script type="text/javascript">
$.ajaxSetup({ cache: false });
$(document).ready(function () {
$('div.onload').each(function () {
var source = $(this).html();
if (source != "") {
$(this).load(source);
}
});
});
</script>
This scans for all DIV that match the "onload" class and reads the REST path from their content. It then does a jQuery.load on that REST path and populates the DIV with the result.
Sorry gotta go catch my ride home. Let me know if you want me to elaborate more.
You have several options.
Create a MVC View User Control and action handler in your controller for the view. To render the view use
<% Html.RenderPartial("MyControl") %>
In this case your action handler will need to pass the model data to the view
public ActionResult MyControl ()
{
// get modelData
render View (modelData);
}
Your other option is to pass the model data from the parent page. In this case you do not need an action handler and the model type is the same as the parent:
<% Html.RenderPartial("MyControl", ViewData.Model) %>
If your user control has it's own data type you can also construct it within the page
In MyControl.ascx.cs:
public class MyControlViewData
{
public string Name { get; set; }
public string Email { get; set; }
}
public partial class MyControl : System.Web.Mvc.ViewUserControl <MyControlViewData>
{
}
And in your page you can initialize your control's data model:
<% Html.RenderPartial("MyControl", new MyControlViewData ()
{
Name= ViewData.Model.FirstName,
Email = ViewData.Model.Email,
});
%>
In rails this is called rendering a partial view, and you do it with render :partial => 'yourfilename'. I believe ASP.NET MVC has a similar RenderPartial method, but I can't find the official docs for MVC to confirm or deny such a thing.
it is very simple you just have to create a strongly typed partial view(or user control) then in your cotroller something like this:
public PartialViewResult yourpartialviewresult()
{
var yourModel
return PartialView("yourPartialView", yourModel);
}
then you can use JQuery to perform the request whener you want:
$.ajax({
type: 'GET',
url: '/home/yourpartialviewresult',
dataType: 'html', //be sure to use html dataType
contentType: 'application/json; charset=utf-8',
success: function(data){
$(container).html(data);
},
complete: function(){ }
});
I found this one line code to work perfectly. orderModel being my model object. In my case I had a helper method in which I had to merge a partial view's html.
System.Web.Mvc.Html.PartialExtensions.Partial(html, "~/Views/Orders/OrdersPartialView.cshtml", orderModel).ToString();