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

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.

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 })

How to create a FileUpload view / viewmodel that isn't an entity in the database

I am working on an auction application and I am creating a method so that the admins can submit an excel spreadsheet that will create a new auction and store it in the database. So first I made a class (model) Uploadfile like this:
[NotMapped]
public class UploadFile
{
[Required]
public HttpPostedFileBase ExcelFile { get; set; }
}
I used NotMapped because I am trying to understand how to create and use models that aren't stored in my database and this is where my issue and misunderstanding lies.
I created a controller, which I did manually since UploadFile is not an entity with a key as such:
public class FileUploadsController : Controller
{
private AuctionEntities db = new AuctionEntities();
// GET: FileUploads
public ActionResult Index()
{
UploadFile UploadFile = new UploadFile();
return View(UploadFile);
}
[HttpPost]
public ActionResult Index(UploadFile UploadFile)
{
if (ModelState.IsValid)
{
if (UploadFile.ExcelFile.ContentLength > 0)
{
if (UploadFile.ExcelFile.FileName.EndsWith(".xlsx") || UploadFile.ExcelFile.FileName.EndsWith(".xls"))
{
XLWorkbook wb;
// in case if the file is corrupt
try
{
wb = new XLWorkbook(UploadFile.ExcelFile.InputStream);
}
catch (Exception ex)
{
ModelState.AddModelError(String.Empty, $"Check your file. {ex.Message}");
return View();
}
IXLWorksheet ws = null;
try // in case the sheet you are looking for is not found
{
ws = wb.Worksheet("sheet1");
}
catch
{
ModelState.AddModelError(String.Empty, "Sheet not found");
return View();
}
var firstRowUsed = ws.FirstRowUsed();
var auctionRow = firstRowUsed.RowUsed().RowBelow();
// create auction
string auctionName = auctionRow.Cell(1).Value.ToString();
DateTimeOffset startDate = DateTimeOffset.Parse(auctionRow.Cell(2).Value.ToString());
DateTimeOffset endDate = DateTimeOffset.Parse(auctionRow.Cell(3).Value.ToString());
string folderName = auctionRow.Cell(4).Value.ToString();
Models.Auction auction = new Models.Auction(auctionName, startDate, endDate, folderName);
db.Auctions.Add(auction);
// find the next table
var nextRow = auctionRow.RowBelow();
while (nextRow.IsEmpty())
{
nextRow = nextRow.RowBelow();
}
const int catNameCol = 1;
var catRow = nextRow.RowUsed().RowBelow();
// get categories from ws table and add to the auction
while (!catRow.Cell(catNameCol).IsEmpty())
{
string catName = catRow.Cell(1).Value.ToString();
int seqNo = Convert.ToInt32(catRow.Cell(2).Value.ToString());
string fileName = catRow.Cell(3).Value.ToString();
Cat cat = new Cat(auction.AuctionId, catName, seqNo, fileName);
auction.Cats.Add(cat);
catRow = catRow.RowBelow();
}
var findNextRow = catRow.RowBelow();
while (findNextRow.IsEmpty())
{
findNextRow = findNextRow.RowBelow();
}
const int itemNameCol = 1;
var itemRow = findNextRow.RowUsed().RowBelow();
while(!itemRow.Cell(itemNameCol).IsEmpty())
{
string itemName = itemRow.Cell(1).Value.ToString();
string itemDesc = itemRow.Cell(2).Value.ToString();
string catName = itemRow.Cell(3).Value.ToString();
string modelNo = itemRow.Cell(4).Value.ToString();
decimal retailValue = Convert.ToDecimal(itemRow.Cell(5).Value.ToString());
string fileName = itemRow.Cell(6).Value.ToString();
decimal initialBid = Convert.ToDecimal(itemRow.Cell(7).Value.ToString());
decimal increment = Convert.ToDecimal(itemRow.Cell(8).Value.ToString());
Cat itemCat = null;
foreach(var cat in auction.Cats)
{
if(catName == cat.CatName)
{
itemCat = cat;
}
}
Item item = new Item(itemName, itemDesc, modelNo, retailValue, fileName, startDate, endDate, initialBid, increment, null, null, null, itemCat);
itemCat.Items.Add(item);
itemRow = itemRow.RowBelow();
}
}
else
{
ModelState.AddModelError(String.Empty, "Only .xlsx and .xls files are allowed");
return View();
}
}
else
{
ModelState.AddModelError(String.Empty, "Not a valid file");
return View();
}
}
db.SaveChanges();
return View();
}
Next I thought I would try to create a view again so that I can display where the user uploads the file and see if my method works and this is where I have run into my lack of knowledge in asp.net.
So I tried to create a ViewModel as I have seen since the model I created before was a data model, so that I could use this viewmodel to display the upload on my view page. My ViewModel is simple and is:
public class FileUploadViewModel
{
public HttpPostedFileBase ExcelFile { get; set; }
}
Now, I wanted to create a view page for this viewmodel and it is still treating this model has an entity and giving me an error that it does not have a key etc. I need a viewpage that can access a model with the Excel file in it and I can't seem to figure out how to accomplish this. I have read up on viewmodels and I know how crucial they are in MVC, however I just can't seem to grasp on how to use them. Can someone please help me understand how to use one here?
Basically, I want to use this view page with my model or viewmodel:
My educated guess is that you are getting stuck in the "Add View" window.
You are probably selecting a template that requires a model (e.g. Create), selecting your FileUploadViewModel class as the model and also your context.
What this does is it causes the Visual Studio "wizard" to try to map the model internally to your context, which results on the error you see.
Instead, select Empty (without model) as the template which will gray out the Model and Data Context fields. Your view will then be created without errors.
You can then tell the view to expect your model by adding this at the top:
#model FileUploadViewModel
Make sure you fully qualify FileUploadViewModel (e.g. include the namespace in front).
Your methods should now use the model you specified at the top of the view:
public ActionResult Index()
{
FileUploadViewModel UploadFile = new FileUploadViewModel();
return View(UploadFile);
}
[HttpPost]
public ActionResult Index(FileUploadViewModel UploadFile)
{
}
You do not need the [NotMapped] attribute anywhere here.

How to display data stored in sessions in mvc c#

I'm storing list of string in to a session. Then I don't know how to get those data to display in my view.
This is my code:
public List<Details> d = new List<Details>();
[HttpPost]
public void getDatas(string destination)
{
XElement rootele = XElement.Load(Server.MapPath("~/XmlFiles/CruiseData/cruiseprodutstwo.xml"));
var getneededData = rootele.Elements("CruiseProduct")
.Where(l => l.Element("Location").Value == destination)
.Select(s => s.Element("Name").Value);
foreach (var itm in getneededData)
{
d.Add(new Details
{
cruiseName = itm
});
}
Session["names"] = d;
Response.Redirect("Check",true);
}
This is my check action method
public ActionResult Check()
{
var chk = Session["names"];
return View();
}
You can store your data in ViewBag, then retrieve them in view:
public ActionResult Check()
{
ViewBag.SessionData = Session["names"] as List<DetailsList>;
Return View();
}
Then in your view, use simply as
#If (ViewBag["SessionData"]!= null){
// Do jobs with SessionDetails what you want
}
Hope this helps.
Controller
public ActionResult Check()
{
var chk = Session["names"];
List<Details> list = Session["names"] as List<Details>;
ViewBag.MyList = list ;
return View();
}
View
#ViewBag.MyList
// e.g.
#foreach (var item in ViewBag.MyList) { ... }
Firstly, it is better to use ViewBag, ViewData and/or TempData when playing with MVC.
The use is quite simple for all the three. Here are the steps :
You assign them some value/object : ViewBag.SomeField = SomeValue;
You use them on your view side : #ViewBag.SomeField.
Here are some link that will definitely get you through :
ViewBag ViewData and TempData
ViewBag ViewData and TempData Basics
Since you are redirecting to an action method here, I would suggest using TempData for your case and using that in the view.
Hope this helps.

List collection from controller to view

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>
}

Categories