Convert model to list before passing it to view - c#

I got this model in my project:
public class ListOfProducts
{
public List<string> ProductNames { get; set; }
public List<string> ProductUrls { get; set; }
}
The way I pass it to my view is:
public ActionResult Index()
{
var listOfUrls = GetListOfHrefs(); //Methods for giving values
var listOfProductNames = GetListOfProductNames();//Methods for giving values
var model = new ListOfProducts {ProductUrls = listOfUrls, ProductNames = listOfProductNames, ProductGtin = listofGti};
return View(model);
}
I would like to pass my model to the view as a list in order to loop through it the way i Want...Can I convert my model to a list before passing it?
Tried model.Tolist() but the intellisense could no find the Tolist-Part
EDIT:
I really need to acess both properties in the same context..In this case the Artice
<article id="post-62" class="post-62 x-portfolio type-x-portfolio status-publish has-post-thumbnail hentry has-post-thumbnail x-portfolio-5e9a5c5e0b6c2e1342bfccc9cacb084f x-portfolio-3ce959340d6fed7ed4f041884b46387c">
<div class="entry-wrap cf">
<header class="entry-header">
<h2 class="entry-title entry-title-portfolio">
<p>#product</p>
</h2>
</header>
</div>
<p>#url</p>
<span class="visually-hidden"><span class="author vcard"><span class="fn">addiadmin</span></span><span class="entry-title">Gluten & Mjölkfri Raggmunk</span><time class="entry-date updated" datetime="2014-05-21T08:23:32+00:00">05.21.2014</time></span>
</article>

its the same to ask "I wanna send MyClass as list ...", this is a basic OOB(Object-oriented programming) concept question IMO..so send List{MyClass} , you are sending one object name ListOfProducts which contains 2 lists, do you mean List{ListOfProducts} ? you can attach any Model , any parameters to the View as you want to them , modify it(any Model /ViewBag.Something) to your needs as you please , you are the game ruler
return View(new List<ListOfProducts >{model});

ListOfProducts is an object with properties that are lists.
I think what you are wanting is
#model ListOfProducts
foreach (var item in Model.ProductNames)
{
....
foreach (var item in Model.ProductUrls )
{
....
EDIT: Following on from your comments, you could do this (but see comments at end)
#for (int i = 0; i < Model.ProductNames.Count; i++)
{
<article id="post-62"...
<div class="entry-...
<header class="entry...
<h2 class="entry-title...
<p>Model.ProductNames[i]</p>
</h2>
</header>
</div>
<p>Model.ProductUrls[i]</p>
....
</article>
}
but this will only work if both ProductNames and ProductUrls contain exactly the same number of elements, in which case perhaps you should re-think your model
public class Product
{
public string Name {get; set;}
public string Url {get; set;}
}
Then create a List<Product> in you `Index' action method and pass that to the view

You cannot currently convert ListOfProducts to a list as it's has nothing to do with a list. It's a new type which you have defined in your code.
if you want it to be a list, you should inherit from IEnumerable for example or ICollection and implement the required functions.
Actually, to implement IEnumerable, you need a property in ListOfProducts that will contain all your List<String> so you could iterate on that !

If I assume that each entry in the list ProductNames matches one entry in ProductUrls, then what your really after is a list of Products and the design is missing the 'Product' class.
Create a class like:
public class Product
{
public string Name {get;set;}
public string Url {get; set;}
}
Now replace your 'ListOfProducts' with:
List<Product>()
Now you have a list of products. Your class ListOfProducts is not required.

Related

Pass Custom View Object from Controller to View

I have a simple problem. In my controller I take join of two tables and return like this:
data = ...
select new { Contacts = item, Applications = items, Answers = j }
This is working fine. I am getting what I want: e.g. 62 data objects with the attribues I want.
But in the view how do I access these set of data points?
simple #model dynamic is not working? There must be some way to do this.
The best way to do that is by creating a ViewModel which will contain all the attributes that you need to display in your view.
public class DataViewModel {
public Contacts {get;set}
public Application {get;set;}
public Answers {get;set;}
}
Create a list of your "DataViewModel"
List<DataViewModel> Datas = new List<DataViewModel>();
After doing that, you will have to assign the values of each element in your controller after getting them from your "data" variable that you created by simply using a foreach loop.
foreach (var instance of data) {
// Assign those values here
}
You'll have to pass the list of your data (ViewModel) to your view from your controller like this :
return View(Datas);
and to call the list of your ViewModel in your view like this :
#model IEnumerable<models.DataViewModel>
Create an 'umbrella' model like:
public DataModel
{
public Contacts contacts {get;set}
public Application applications {get;set;}
public Answers answers {get;set;}
}
On controller:
select new DataModel(){ Contacts = item, Applications = items, Answers = j }
And have on View:
#model DataModel
Class
public DataModel
{
public Contacts {get;set}
public Application {get;set;}
public Answers {get;set;}
}
Controller
DataModel model = new DataModel();
model.Contacts = items;
model.Application = item;
model.Answers= items;
return View(model);
View
#model DataModel
// will get all three tables data here
#Model.Contacts
#Model.Application
#Model.Answers

how to build html navigation bar dynamically using data from database

I have this data from database with self relation
Parent_ID Name Child_ID
1 cities null
2 Egypt 1
3 Saudi 1
4 technology null
5 vb.net 4
6 c# 4
Now i want to build html navigation bar using this data
To be like the following
<ul>
<li>cities
<ul>
<li>Egypt</li>
<li>Saudi</li>
</ul>
</li>
<li>technology
<ul>
<li>vb.net</li>
<li>c#</li>
</ul>
</li>
</ul>
I don't know what is the best way to da that
My be xml node or my be using linqu ...
Whatever the best way help me please.
you can use asp:reapeater control provide datasource to it and give html format inside it. The easiest and the efficient way.
Explore it more....
Edited: You must mention
in mvc, you can pass data inside viewBag, viewdata whatever you like and on view you can use foreach iteration and inside it generate the required html
like
ViewDate["data whatever"] = your data
and on html
#foreach(var item in ....)
{
<a href='item.whatever Value'>
}
OK, here is one method of creating a n deep menu viewmodel
grab all the data from the table with one select and populate a list of menuItemMVs. create a menuMV object and put this list in the static AllMenuItems list. create a razor view for the root of the menu and bind it to menuMV. create a partial view for a menu item which binds to menuItemVM this should contain a for loop looping through the childern and recursively calling RenderParital itself (the partial view) for each child in the menuItemVM it is rendering.
get your root menu razor to loop over the rootMenuItems and renderpartial your menuitem partial view for each
public class menuVM
{
public static List<menuItemVM> AllMenuItems { get; set; }
public IEnumerable<menuItemVM> rootMenuitems
{
get { return menuVM.AllMenuItems.Where(c => c.ParentId == null); }
}
}
public class menuItemVM
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get;set; }
public IEnumerable<menuItemVM> Childern {
get
{
return menuVM.Childern.Where(c => c.ParentId == this.Id);
}
}
}
ps. I think you have childId and parentId the wrong way around in your
sample data

Custom Select List Item

I am attempting to rid my code of the dependency on System.Web.Mvc, since I have extracted my model out to a separate .dll (outside of the MVC project) so that it can be shared among many projects.
I am attempting to create a "custom SelectListItem" which is simply just a class with two properties of string Text and string Value and looks like:
public class DropDownListItem
{
public string Text { get; set; }
public string Value { get; set; }
}
However, I am trying to find a way to pass this object into a DropDownListFor in my view. Is there anyway to manipulate this so that I can do something like:
#Html.DropDownListFor(x => x.Value, Model.Values, new { #class="form-control" })
Where Models.Values is of type List<DropDownListItem>.
Yo don't need to create a DropDownListItem class - instead you can create your own POCO (Plain-Old-C#-Object) to contain List Options:
For example, let say you have the following class :
class MyClass
{
public int Id {get; set; }
public string name {get; set; }
}
to have dropDownlist which contains a list of MyClass, you can simply use :
#Html.DropDownListFor(model => model.Entity.Id, new SelectList(MyClass, "Id", "Name"))
The id represent the value of the selection, and the name will be the text displayed within the DropDownList.
Hope this helps!
You can put the list item in viewbag and get the value in your view like these:
#Html.DropDownList("Ligas")
and your codebehind
Modelo.AdminSitio = Modelo.GetAdminSitio();
ViewBag.Ligas = new SelectList(Modelo.AdminSitio.ListadoLigas, "Value", "Text");
when listdoLigas is equals
ListadoLigas= (from x in db.Ligas select new DropDownListItem { Value = x.Oid_Liga, Text = x.NombreDeLiga}).ToList();

How can I return multiple values with a select list in ASP.NET MVC?

For example if I had a dropdownlist
#Html.DropDownListFor(model => model.proj.price, Model.FoodSelectList, "Choose...")
The list displays a bunch of foods and each food has a price value that is returned when a food is selected. I would also like to store the name of the food item selected. How could I get both values back from the select list?
Thanks for the help I used something similar to this javascript
<script>
function myFunction()
{ var alertinfo = document.getElementById("Project_Price");
var Project_Names = alertinfo.options[alertinfo.selectedIndex].text;
$('#Project_Name).val(Project_Names);
}
</script>
Create a hidden field for the name:
#Html.HiddenFor(m => m.FoodName)
where FoodName is a property on the view model to store the name of the food. Then in JavaScript, leveraging jQuery here, set that value:
$('#{name_of_elem}').change(function() {
// set yourVal somehow here
var yourVal;
$('#FoodName').val(yourVal);
});
where {name_of_elem} is the name of the drop down element. I think it's going to be proj_price, but I can't be sure, just look at the generated HTML.
It sounds like what you really need is a Food model which contains these values. Over-simplifying it might look like this:
public class Food
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Then in your view model you'd select the ID of the corresponding Food items, rather than the price or the name. So the select wouldn't contain the actual data, just a reference to the data. Its value would be the ID and its text would be the name (or price, or a combination thereof, whatever you want to display). Something like this perhaps:
#Html.DropDownListFor(model => model.proj.FoodID, Model.FoodSelectList, "Choose...")
In server-side code, given the ID of the entity selected, you'd fetch the entity itself from whatever the underlying data store is and then you'd have all of the information about that entity. For convenience it could even be lazy-loaded from the view model. Something like:
public int FoodID { get; set; }
public Food Food
{
get
{
return Food.Fetch(FoodID);
}
}
There are plenty of ways to accomplish that, some may fit your model structure more than others, so this is just an example to illustrate the idea. But the main point is that the select would be referencing the entity instead of trying to contain the entity, since a select (and HTTP POST values in general) is really just a key/value pair.

C# MVC3 ViewBag, how to use lists property in view within foreach statement?

public class RegisterSubscription
{
public string ID { get; set; }
public string Description { get; set; }
public int SubscrSelected { get; set; }
public string Image { get; set; }
public string InfoUrl { get; set; }
}
private List<RegisterSubscription> activePlans = new List<RegisterSubscription>();
In my controller I have ViewBag.ActivePlans = activePlans; and the ViewBag fills with the correct data. Now in my view I have:
#foreach (var item in ViewBag.ActivePlans)
{
<li class="popupmenu" id="service_#(item.ID)" >
<div>
#Html.Image(item.Image, new { style="border-style:none; text-align:left; vertical-align:middle; width:64px; height:64px" })
</div>
</li>
}
but I get the following error:
'System.Web.Mvc.HtmlHelper' has no applicable method named 'Image' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
Any help will be greatly appreciated,
thank you in advance.
Warning: I haven't done any MVC stuff, so this is guesswork.
My guess is that ActivePlans is dynamic in some form... so you basically need to make item strongly typed. It may be just as simple as this:
#foreach (RegisterSubscription item in ViewBag.ActivePlans)
... which would basically cast each item to RegisterSubscription as it got it out of the ViewBag. After that point, I can't see that you've got anything dynamic, so the extension method should be okay. I think. Maybe. When the wind is right.

Categories