List collection from controller to view - c#

hi i am doing my project in mvc4 using c#
i have list in my controller
public ActionResult Gallery()
{
string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
List<String> currentimage = new Gallery().GetGalleryName(folderpath);
return View(currentimage);
}
i want to list the items in currentimage in my view , how it possible, i am trying the following
#model List<String>
#foreach(var item in Model)
{
<p>
#item // what will be write here..
</p>
}

Related

I have a .txt file and I should scroll and print each element on the screen (list of strings)

I have a .txt file and I should scroll and print each element on the screen (list of strings).
I am new and inexperienced, can you please help me write the file ndex.cshtml (view)?
(Class.cs)
public class Reader
{
public static List<string> Read(string path)
{
var result = new List<string>();
String line;
try
{
StreamReader sr = new StreamReader(path);
line = sr.ReadLine();
while (line != null)
{
result.Add(line);
line = sr.ReadLine();
}
}
catch (Exception e)
{
result = new List<string>();
}
return result;
}
}
}
(HomeController.cs)
{
public class HomeController : Controller
{
public ActionResult Index()
{
var result = Reader.Reader.Read("......txt");
return View(result);
}
Depending on how you want to render the view...
View.cshtml
You can specify a List as your type of model if you wish instead of introducing your own abstractions. Here is a partial view:
#model List<string>
#{
Layout = null;
}
<ul>
#{
foreach (string line in Model)
{
<li>#line</li>
}
}
</ul>
In the razor view you can iterate through the strings in the foreach. Here I'm putting the output in an unordered list.
You can add c# code to execute in the view using the # blocks. #{ } will put in a block of code to execute.
Reading text file
You can also read all lines from the text file using:
string[] lines = System.IO.File.ReadAllLines(#"...filename.txt");
Putting the full path to the filename. Then you could change your type of model to Enumerable<string> as we are only enumerating through the collection.
I just created a demo project in github, to display text lines in html. The OP also mentioned scroll and print, but that should be considered only after succcesfully display those lines. So this demo can be a start for the OP.
Also paste main code here. I'm using Razor pages.
Code behind
public class IndexModel : PageModel
{
//other lines...
public string[] Lines { get; set; }
public void OnGet()
{
// you need change the fullName, and may need some exception handling
string fullName = Path.Combine(_hostEnvironment.WebRootPath, "js/site.js");
Lines = System.IO.File.ReadAllLines(fullName);
}
}
Razor
<div class="text-center">
<h1 class="display-4">This is text lines</h1>
#foreach (string line in #Model.Lines)
{
<p>#line</p>
#*add a hr to distinguish lines*#
<hr />
}
</div>

How to call View method and pass parameter to method?

I have a list of categories in the Sidebar.
#foreach (var item in Model) {
<li>#item.Title</li>
}
And I want to display the products of this category by clicking on the category. To do this, I implemented the method ViewCategory.
public ActionResult ViewCategory(string name) { ... }
But I do not know how to pass the parameter correctly. I'm trying to write something like that, but I understand that doing something wrong ...
#Html.Action("ViewCategory", "Books", new {Title=item.Title})
Help me please
UPDATE
I have a View Index, and a method in which I bring up a list of my products
public ActionResult Index()
{
HttpResponseMessage response = WebApiClient.GetAsync("Books").Result;
var booksList = response.Content.ReadAsAsync<IEnumerable<BookDto>>().Result;
return View(booksList);
}
I need to display only products that belong to this category when choosing a category. I list the categories with PartialView
<ul>
#foreach (var item in Model) {
#*<li></li>*#
#Html.Action("ViewCategory", "Books", new { name = item.Title })
}
To do this, I wrote a method that I try to use instead of
public ActionResult ViewCategory(string name)
{
HttpResponseMessage responseBooks = WebApiClient.GetAsync("Books").Result;
List<BookDto> booksList = responseBooks.Content.ReadAsAsync<IEnumerable<BookDto>>().Result.ToList();
for (int i = 0; i < booksList.Count; i++)
{
if (booksList[i].CategoryName != name)
{
booksList.Remove(booksList[i]);
}
}
return View("Category");
}
But now I have NullReferenceException...
Just change
#Html.Action("ViewCategory", "Books", new {Title=item.Title})
to
#Html.Action("ViewCategory", "Books", new {name = item.Title})
You can use it as following.
#{ Html.RenderAction("ViewCategory", "Books",
new {param1 = "value1", param2 = "value2" }); }
You can try using
#Html.Action("Controller","Name", new { name = item.Title })

List in model to controller to view?

I'm learning MVC 5 and I can't find the reason why I can't reach the List of names in the View? I'm sure I have done something wrong, but I can't see why and would preciate some help to be able to continue.
In the Controller I have tested to use ViewBag and pass the List with return and then use #Model.
Model Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_1.Models
{
public class ListNames
{
public static List<string> names;
// Constructor
public ListNames()
{
// Create list
names = new List<string>();
// Add some names to list
names.Add("Anna");
names.Add("Linda");
names.Add("Petra");
}
}
}
Controller:
public ActionResult ListNames(List<string> Names)
{
ViewBag.Name = Names[0];
return View(Names);
}
View:
#model MVC_1.Models.ListNames
#{
ViewBag.Title = "ListNames";
}
<h2>ListNames</h2>
<p>#ViewBag.Name</p>
<p>#Model.????</p>
You forgot to add get and set to the list inside the model;
public class ListNames
{
public List<string> names { get; set; }
//rest of the code
}
As #stephen-muecke mentioned you action returns List<string> and the view is expecting the ListNames model. A solution will be like below
public ActionResult ListNames()
{
var listNames = new MVC_1.Models.ListNames();
ViewBag.Name = listNames.names[0];
return View(listNames);
}
View:
#model MVC_1.Models.ListNames
#{
ViewBag.Title = "ListNames";
}
<h2>ListNames</h2>
<p>#ViewBag.Name</p>
#foreach(var name in Model.names)
{
<p>#name</p>
}

How to pass ID to default value of another view

I have a list of incidents which can have associated jobs. I Have a separate views for incidents and jobs. From the incident index page I have the following link to create a new job for that incident:
#Html.ActionLink("Create","Create", "Job", new { id = item.IncidentID }, null)
which takes the incident ID from that field and loads the Job view. I want to pass the ID as a default value for creating a new job, so the job will be assigned the incident ID.
I made this controller:
public ActionResult Create(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var newid = id;
ViewBag.ActionCode = new SelectList(db.ActionTypes, "ActionCode", "ActionType1");
ViewBag.IncidentID = new SelectList(db.Incidents, "IncidentID", "DefectFreeText");
return View();
}
How can I assign a default value to the form on the create job view ? I thought something like this:
#Html.EditorFor(model => model.IncidentID, id/newid)
Can anyone help me figure out what I am doing wrong?
I am assuming you want to set a default item for your Incidents dropdown list when user pass that to your create action method as a querystring. I would avoid using ViewBag approach to transfer your dropdown list data to the view and switch to a strongly typed viewmodel approach.
First create a viewmodel for our create view.
public class CreateJobVM
{
public int IncidentID { set;get;}
public int ActionTypeID { set;get;}
public List<SelectListItem> ActionTypes { set;get;}
public List<SelectListItem> Incidents{ set;get;}
public CreateJobVM()
{
ActionTypes =new List<SelectListItem>();
Incidents=new List<SelectListItem>();
}
}
And in your GET view,
public ActionResult Create(int? id)
{
var vm=new CreateJobVM();
vm.ActionTypes=GetActionTypes();
vm.Incidents=GetIncidents();
if(id.HasValue)
{
//set the selected item here
vm.IncidentID =id.Value;
}
return View(vm);
}
Assuming GetActionTypes and GetIncidents method returns a list of SelectListItems, From a DB table/ XML /whatever place you have data
public List<SelectListItem> GetActionTypes()
{
List<SelectListItem> actionTypesList = new List<SelectListItem>();
actionTypesList = db.ActionTypes
.Select(s => new SelectListItem { Value = s.ID.ToString(),
Text = s.Name }).ToList();
return actionTypesList;
}
and in your view which is strongly typed to CreateJobVM
#model CreateJobVM
#using(Html.Beginform())
{
#Html.DropDownListFor(s=>s.ActionTypeID ,Model.ActionTypes)
#Html.DropDownListFor(s=>s.IncidentID,Model.Incidents)
<input type="submit" />
}
When you post the form you can check the property values to get the values user selected in the form
[HttpPost]
public ActionResult Create(CreateJobVM model)
{
//check for model.IncidentID, ActionTypeID
// to do : Save and redirect
}
Just pass it with the help of ViewBag/ViewData
ViewBag.DefaultId=id;
return View();
If you have a model based view
YourViewModel.DefaultId=id;
return View(YourViewModel);
In View,
#ViewBag.DefaultId
or with ViewModel
YourViewModel.DefaultId

How to pass info to View from Index in this scenario - MVC3

I have written following code:
public ActionResult Index()
{
var folders = Directory.GetDirectories(Server.MapPath("~/Content/themes/base/songs"));
foreach (var folder in folders)
{
var movieName = new DirectoryInfo(folder).Name;
string[] files = Directory.GetFiles(folder);
string img = string.Empty;
List<string> song = new List<string>();
foreach (var file in files)
{
if (Path.GetExtension(file) == ".jpg" ||
Path.GetExtension(file) == ".png")
{
img = Path.Combine(Server.MapPath("~/Content/themes/base/songs"), file);
}
else
{
song.Add(Path.Combine(Server.MapPath("~/Content/themes/base/songs"), file));
}
}
}
return View();
}
What i am trying to do is pass 20 movie names with movie images and each movie has about 4 or 5 songs that should display under it. I have figured out how to capture all this info above but i am not sure how to pass it into view to Display. Can someone please help me?
You should add some class to your application i guess. For example Movie and MovieSong and your Movie class should be has something like IList Images. Then you can pass your movies to your view easily.
I'm not sure whether this code working or not but you can try something like this:
public ActionResult Index()
{
var movies = new List<Movie>();
var songsPath = Server.MapPath("~/Content/themes/base/songs");
var folders = Directory.GetDirectories(songsPath);
foreach (var folder in folders)
{
Movie movie = new Movie();
movie.MovieName = new DirectoryInfo(folder).Name
string[] files = Directory.GetFiles(folder);
foreach (var file in files)
{
if (Path.GetExtension(file) == ".jpg" ||
Path.GetExtension(file) == ".png")
{
movie.Images.Add(Path.Combine(songsPath, file));
}
else
{
movie.Songs.Add(Path.Combine(songsPath, file));
}
}
movies.add(movie);
}
return View(movies);
}
You should populate a model object... and pass it in the return line:
var theModel = new MyModel();
...
//All the loading model info
return View(theModel)
In your View, you need to set a line in the top as follow:
#model YourProject.MyModel
Then, you do the looping throught the #Model object.
Q1. i am not sure how to pass it into view to Display
A. You need to use View Model for this, below is a ViewModel that I have prepared for this.
public class Movie
{
public string Name;
public string ImagePath;
....
....
//Add more as per your requirement
}
Push all the data you have into this Model prepared.
Q2. What i am trying to do is pass 20 movie names with movie images and each movie has about 4 or 5 songs that should display under it
A. Now as what you have is a collection of movies you will need to pass a list of this Movie class to the Model.
public ActionResult Index()
{
var movies = new List<Movie>();
// populate the data
return View(movies);
}
Display it in View
#model ProjectName.Models.List<Movies>
#foreach(var item in Model)
{
<h1>Movie Name : </h1> #item.Name
....
.... //etc etc
}
Hope this helps.

Categories