Get data into MVC view - asp.net-mvc

I have to populate a javascript function with some information from my DB, is the best way to access via the controller and pass it through(I'm not sure how to pass an object) or is it easier to have the view to retrieve the data?
i have to create an object in javascript something like this
new FleetSelector([{ "OwnerId": "2df3893d-c406-48fe-8443-1622ddc51af2", "DisplayName": "Navman Dev" }, { "OwnerId": "7A402CD7-5EEA-4AF5-80A3-22EED0610C9D", "DisplayName": "CORSA TRANSPORTES" }]);
}
so is there a way to pass an list of objects that i can loop through in my view to be able to make that javascript?

Related

pass observable from one view model to another in knockout.js

Within a view I have a button which navigates to another view 'addWork'.
I want to pass an observable from the view model to the view model associated with the addWork view.
I already have addWork within the constructor for the view model, I'm just unsure what else to do.
The url action on the ko.applybinding is as follows, this work fine, I just need to amend so I'm passing the observable.
"#Url.Action("AddWork", "Work")")
The button is bound to this function:
self.AddWork = function () {
window.location.href = addWork;
}
An observable is purely a javascript concept and typically won't survive being sent to the server and back. You would be better off sending just the contents of the observable instead of the observable itself.
If you just need to send an ID then with asp.net MVC you can put it into your #Url.Action statement like Url.Action("AddWork", "Work", new { id = myID });

OData PUT to replace collection property

Using the OData standard is it possible to replace collection by sending a new collection?
Scenario:
The person object contains a list Address object. I would want to replace the Address collection with a new collection.
PUT Persons(1)/Addresses
[{"city": "X", "country": "US"}, {"city": "Y", "country": "US"}]
This is not possible out of the box (at least for ODATAv3), as the default routing template does not expect segments after the key portion.
But you should be able to add an ODATA Action that would do what you want to achieve. Your action definition could then look similar to this:
var action = builder.Entity<Person>()
.Action("Addresses")
.Returns<bool>();
action.Parameter<Collection<CityCountryPair>>("data");
The type CityCountryPair would be a regular DTO containing your properties you want to change. Make sure this type is also registered as an EntitySet in Odata or use a plain map/dictionary with only primitive types.
The actual call to the ODATA action would then look similar to this:
POST http://www.example.com/api/YourEndpoint/Persons(42)/Addresses
Content-Type: application/json
{
"data" :
[
{ "city" : "Berne" , "country": "CH" },
{ "city" : "Y" , "country": "CH" }
]
}
If you want to send more complex data types you can still resort to a customer JSON Deserialiser and override the default one or use a custom model binder after all.

How to call method of a controller from View without using ajax in ASP.NET MVC?

I am developing MVC application.
I am in situation that, I want to call the method of controller from View.
I don't want to use the Submit button (If I use it goes to create method.) either I dont want to use ajax ....
I want to know that what are ways to call the method of controller from view...
Other than submitting form process or other than ajax call.
Ex. I have a form in which user fills all the data and save it... After submit button it saves the data in DB and Saved data displayed. Now, After saving I want to transfer/pass that data from that view to another view... but I cant find appropriate method for it.
Please check image below...
I have this view after saving...now when I click on 'Click Here' Link , I want to pass the same data to another view to show the preview... some other format...
So I am stuck on how to pass the same data ? I cant use submit as it already saved... I cant use ajax as its not partial stuff... I want to pass the entire to to another view...
If you have the order saved in a database on the server, you would typically pass through the ID, rather than the "entire data" to the controller method, and reload the data from the DB in order to render the other view. Is this what you're after?
View code:
...sent successfully. #Html.ActionLink("Click Here", "Status", new { id = Model.Id }) to check status
Controller Code:
public ActionResult Status(int id)
{
var order = Repository.Get<Order>(id);
return View(order);
}

Can i pass JSON instead of Model from my controller to my Razor view

I have a view that inherit the following:-
#model MvcApplication.Models.Application
But i need to know if it is possible to pass JSON objects to my view in the same way i am passing the model objects?
Since i have the following Controller:-
public ActionResult ListPackages()
{
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
//code goes here ....
return Content(json, "application/json");
}
}
which returns JSON using a API call, and then i am displaying the JSON on the view using JavaScript as follow:
$.ajax({
url: $('#geturl').data('url'),
type: 'GET',
cache: false,
success: function (result) {
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str })
.appendTo($('#products'));
});
}
The problem with displaying the JSON using JavaScript is that it will make too difficult for me to work easily with the JSON objects, such as creating links based on the returned JSON or creating table that contain the JSON. So my question is: Is it possible to pass a JSON object instead of a Model object from my controller to my view?
Server- vs client-side confusion
You're talking two things here:
Creating a view: controller passes model to the view on the server side and it doesn't make much sense to do so using JSON, because an in-memory object is being passed to view engine.
Consuming JSON data on the client: what you're talking about here is client-server Ajax communication where you request data from the client and get JSON returned from the server. This has arguably nothing to do with model data being passed to the view
Best solution using JSON
In order to easily consume JSON data (in your case it's an array of packages) on the client to generate resulting populated HTML is to use some sort of templating on the client side. jQuery used to have non-final templating plugin which is now a separate project. I've had great experience with it but there are other plugins as well. Use the one that you feel most comfortable with its syntax.
Where to put those templates?
If you know the structure of your JSON objects passed from the server at the point of creating your view, you can put templates in the view itself and they'll just wait untill being used on the client.
If you don't know the structure of your JSON objects then you'll have to pass templates either along JSON object or as a separate request.
The first approach is the usual one, the second one is rarely used and is much more dynamic.
Best solution not using JSON
If you don't like parsing JSON to HTML results (either manually or using templates), you can always make Ajax requests to your controller action, which would return a prepared HTML as a partial view instead of JSON result. This way, you could easily just put that HTML onto your page without any JSON data manipulation.
What do you gain here? Well suppose you have this functionality in your app:
You have a view that displays a paged list of packages.
When user first accesses the page first page of packages are being returned
Paging to next page is done via Ajax and the list is being replaced by returned data
If you'd create a partial view for your subsequent Ajax request, you can use the same partial view in your main view to display the first page of packages. This will ensure that you only have to change one partial view and display would change on inital page load as well as subsequent package paging.
If you used view + JSON + templating that means that you have to maintain two presentations of package list: the one being used in the view for the first page and the template that displays subsequent paging.
Which one then?
All things being equal it makes the second solution better. But the choice of course depends on your case (of things not being equal) and you should be able to determine which one is best in your scenario.
No, you can't. A view must be strongly typed to a model. So one solution would be to deserialize this JSON into a model object before passing it to the view:
public ActionResult ListPackages()
{
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
//code goes here ....
var model = new JavaScriptSerializer().Deserialize<MyViewModel>(json);
return View(model);
}
}
where MyViewModel would of course reflect the JSON structure that you are working with.

How to Work with a Backbone.js Model and Views or Rails with a Deeply Nested JSON Object

I'm new to Backbone.js and working with JSON.
I'm having trouble working with the following JSON:
http://pastebin.com/FFEwc0Fb
What I want to achieve is to
create a model of that JSON data
bind the model to a view
bind the view to a template and learn how to show certain attributes of the data e.g. feed->title and the titles of each playlists which is feed->entry->array->title
Could someone provide sample code of that does the above or point me in the right direction?
Possible Alternative Solutions: I'm also using Rails in my App so I could use try using Rails to turn the JSON into the JSON I want it to be ...
look at the parse method on models and collections. After you make your fetch the response is always passed through a parse function that you define on your model or collection. In there you can go through the object and build up the attributes to be set to the model how you want them. For example:
parse: function(response) {
var attrs = {
title: response.feed.title,
author: response.feed.author
};
return attrs;
}
That's a small example of how you could do it within backbone.

Resources