pass value from apicontroller to view in asp.net mvc4 - c#

I have list of data in my api controller.
I want to pass this data to view using something similar to viewbag.
I know we cant use viewbag in apicontrller , So Is there any alternative for it.

Normally ApiControllers do not return views. They return models, or HttpResponseMessage for that matter. So you could simply have a view model that will contain the required property and then have your API action return this view model.

You are not supposed to tho that, the API controllers return only data (XML, Json, etc). So you should have two controllers:
System.Web.Http.ApiControlle Use this to return collections of data for example:
public List<Company> Get()
{
return this._companyService.GetCompanies();
}
Returns a list of companies in Json or XML not a view.
System.Web.Mvc.Controller use this one for returning HTML without data for example an HTML table without rows or client-side templates.
How to link the two? The idea is to render in the client-side with JavaScript, there is a good few reasons to do it this way, the main ones are that you have data and presentation in two completely separated feeds so you will be able to re-use your data feed (in mobile apps for example).
To render in the client-side is good idea to use some JavaScript rendering engine, take a look to http://handlebarsjs.com/.
Use Jquery.getJSON() to get your JSON and get your handlebars template from your DOM or via Ajax, select a DOM alement to insert the generated HTML. Once you have the JSON, template and container use the function below:
function RenderJson (json,template,container) {
var compiledTemplate = Handlebars.compile(template);
var html = compiledTemplate(json);
$(container).html(html); //set new content
}
I know it can seem like a more complicated process but it you try it you will see the advantages, you will be able for example to test your data feed and your data presentation separately.
Hope it helps :)

Related

What is the better way to reload a part of the view with new data in ASP.Net MVC?

Currently, I have many tables in my view. For the first time, I am loading it with the Model property values in HTML.
But I have to reload the tables based on the change in a dropdown box. For that, I am making an ajax call and with the new data, I am replacing the table in the client side(Javascript).
Now, I wish to know, Is there any other better way to do this functionality? Like Asp.Net engine itself takes care of loading that particular table with new data, so that I don't want to recreate the html structure in JS.
Will the partial views help me in this case?
This is not the full answer, just an idea on what you could do:
Create controller
public class RenderPartialController
{
[HttpGet]
public IActionResult RenderPartial(string viewName, string data)
{
//do something with data
//create model for that view
return View(viewName, model);
}
}
Then in js you can make ajax call and replace html with data from response
function updatePartial(viewName, dataObject, selector){
let data = JSON.stringify(dataObject);
$.get(`...RenderPartial?viewName=${viewName}&data=${data}`, res => {
$(selector).html($(res).find(selector).html());
});
}
updatePartial('_TableView', {id: 1}, '#mainTable');
Please remember, that if you had any JS bindings in the old html, they will be removed and you will need to reapply them.
That is just an idea, not the solution

Creating partial view with dynamic content

I understand when I create a view, I shouldn't be putting any code in there besides html and the data from the model/controller, which is what I've done so far.
But lets say there is a snipped of dynamically generated html that can be used in multiple views, I'm guessing this would be a partial view that goes in the Shared folder in the project. But since it's a partial view, that has no absolute controller to handle it's propagation of dynamic data (from db), how would I call, and where would I code the propagation of data from the db into the view (or model?), if lets say the partial view was to dynamically render content for table.id=n, etc.
I'm fairly to new and working off a tutorial in .net, trying to figure out how to do this. Anyone know how it's done? Hope the question makes sense.
You can always define a model for the partial.
And you can render the partial from the container view passing a dinamically populated instance of its model:
<!-- index.cshtml -->
<h1>Feed Upload</h1>
<div id="uploader">
#Html.Partial("~/Views/Shared/Controls/_FileUploader.cshtml", new FileUploaderModel() { UploaderClassName = this.Model.UploaderClassName })
</div>
In this simple example I call the partial _FileUploader.cshtml from the index.cshtml using the #Html.Partial() method, passing a new model instance that specifies the UploaderClassName value.
Edit
The this.Model.UploaderClassName refers to the container's model and it is initialized inside the container's controller business. Of course the container's controller can run any data access logic to grab dynamic data from the db and pass them to the partial's model.
Have a look at MSDN, and at this article.
Assuming you are using the razor view engine, you can put an .cshtml file in the App_Code folder with helper functions.
The syntax is like this:
#helper FormatDate(DateTime date)
{
#date.ToShortDateString()
}
You call it like this (assuming the file is Utility.cshtml)
#Utility.FormatDate(Patient.DOB)
Because you can pass parameters to a helper, you can pass any type you need, including complex objects.
I recently published a nuget package to do this very thing. It's called Dynamic MVC.
http://dynamicmvc.com
You can look at the source code on codeplex.
https://dynamicmvc.codeplex.com
The way I did this was to use the ModelMetadata engine built into MVC to allow me get the value for any property in a weakly typed fashion. The ModelMetadata engine originally came from ASP.net Dynamic Data and was ported over to MVC in MVC2. It works great for this kind of situation.

Why Using JSON in MVC application?

First i would like to apologize if this is a stupid question.
While learning MVC i came a cross creating a strong type views based on model which for example will display all Users by 2 different functions, first will return a View passing a collection of users second will return a collection of JSON objects. so my question is, as i'm not familiar with JSON and for me using Models are more clear, why then using JSON in MVC?
In short why using:
var users = _db.Users
.Where(r => r.Name.Contains(q))
.Take(10)
.Select(r => new { r.Name,r.LastName,r.Address.Country });
return Json(users, JsonRequestBehavior.AllowGet);
In place of:
var users= _db.Users
.Where(r => r.Name.Contains(q))
.Take(10);
return View(users);
Maybe this is a bad code example, but why converting Models to Jason before passing them to a view, if we can directly pass the models.
For the first code snippet, it is more likely that it is used for a ajax call to seamlessly load the data from the server to the client and perhaps keep refreshing it without reloading the page. Also, the Users entity may have much more information than needed by the client, so the first example is reducing the information served and doesn't require you to create a new model to represent it.
The second example would be a controller action actually returning a view and that view is strongly typed.
If you would make a project that uses the WebApi, you wouldn't return views, you would expect the client to ask for data and that the client renders it how it sees fit.
If you want the call to return HTML that can be rendered in a browser, you would return a View, which basically takes the data and applies it to an HTML template.
If you want the call to return data only (most likely to be processed by an AJAX request), then you would return JSON.
The first is going to return JSON with a content type of application/json while the latter will return html with the content type text/html (after the appropriate View Rendering Engine has rendered the view in question) - they can be considered two different representations of the same resource. You may want to return JSON in response to a request made via AJAX and return only the data from the model that is required, but you may want to return HTML in response to a "normal" request.
out of the box, ASP.NET MVC does not support Content Negotiation, that is, make a request with the Accept header set to a particular MIME type will likely not yield a response with the expected content type - controller actions will in the majority of cases be configured to return a resource in one particular content type (usually html). ASP.NET Web Api on the other hand does support Content Negotiation out of the box.
JSON (= data only) is generally used in asynchronous (AJAX) requests as they can easily be processed by Javascript, while Views are styled HTML responses ready to be displayed by the browser.
Client side libraries understand JSON very well, so if you want to parse the result and manipulate them using a client side framework/custom scripts, then JSON is a better option (AngularJs is one example).
In Addition to your question, when using JSON, first you convert Model to JSON but when you users post a request you might reconvert JSON to model in order to persist result to DB. :-)
I

How can I generate client-side view models for knockout in an ASP.NET MVC project?

I am currently working on an ASP.NET MVC solution and have recently introduced both Knockout (an MVVM JS library) and Wijmo (a set of jQuery UI widgets).
With the introduction of Knockout I also need to have models on the client side, so for this purpose I am serializing the C# ViewModel and attaching it to the view using data-model="#Model.ToJson()". This allows me to retrieve the model from JS and apply some client-side love to everything.
However, knockout needs everything to be observables, so I need to declare a separate client-side ViewModel and map everything from the data-model object. This feels very much like duplicate effort and I'd like to avoid it somehow.
I'm hoping someone has a tool or technique to share that will allow me to render the knockout ViewModel directly from the server. Possible solution could include:
Custom JSON serialization to render the observable view model directly to the output in the data-model attribute.
Automatic client-side transformation (I've heard of ko-autobind, but am not sure if it would be a recommended path to take or how stable/complete it is)
Something I haven't thought of
I'd like the solution to be generic and automatic, as my current approach of typing the observable client-side view models by hand is just too unproductive to be viable.
How are you solving this problem?
According to their tutorials it's just a simple .map function
If this is the ViewModel
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
And this function get's the data from the server, it uses the .map function to inject the server data right into the VM
// Data
var self = this;
self.tasks = ko.observableArray([]);
// Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("/tasks", function(allData) {
var mappedTasks = $.map(allData, function(item) {
return new Task(item)
});
self.tasks(mappedTasks);
});
For ko mapping
http://knockoutjs.com/documentation/plugins-mapping.html
For auto-bind here's an example
https://groups.google.com/forum/#!msg/knockoutjs/IJTx37UXQVw/UTrWdEK1C-oJ
Try this pluggin for visual studio
http://visualstudiogallery.msdn.microsoft.com/32c15a80-1c54-4e96-a83f-7cd57573a5d2

.net web service

i am calling a web service by aspx page and wants my return output as a json format with a specific view like (grid view) in asp.net...so here is any view available in JSON which display my output like grid view..pls give me suggetion as soon as possible....thax
salman ansari
As far as I know, WebServices are based on XML SOAP objects, I anot sure if these can be handled like Json objects or converted. You could create a page (or view in MVC), that returns json objects specifically.

Categories