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 })
Related
I have the following code in the controller portion of an MVC5 project.
public ActionResult Index()
{
insightly Insightly = new insightly(xxxxx);
String Contact;
var IContact = JsonConvert.DeserializeObject<dynamic>(Insightly.GetContacts().ToString());
// var IContact = JsonConvert.DeserializeObject<dynamic>(insightly.GetContact(CONTACT_ID).ToString());
List<string> Contacts = new List<string>();
foreach (var item in IContact)
{
Contact = item.SALUTATION;
Contacts.Add(Contact);
}
Response.Write(Contacts.Count);
return View(Contacts);
}
Everything works great, but I am having trouble with the Razor syntax on the view side for the DropDown box.
Has anyone ever done this?
Instead of returning a List of type string, return a List of type SelectListItem. Iterate over your contacts and add a selectlistitem for each contact e.g.:
List<SelectListItem> listItems= new List<SelectListItem>();
foreach (var contact in Contacts)
{
listItems.Add(new SelectListItem
{
Text = contact,
Value = contact
});
}
In View:
#Html.DropDownList("NameForList",
Model.listItems,
"Please Choose",
new { #class = "form-control" })
I had used select list item in controller action and pass the select list item values to another controller action by passing in parameter but didn't get any values in another controller action
// first controller action
List<SelectListItem> dropdownItems = new List<SelectListItem>();
foreach (var item in (IEnumerable)singlecheckbox)
{
int Id = Convert.ToInt32(item);
dropdownItems.AddRange(new[]{
new SelectListItem() { Text = null, Value = Id.ToString() }});
}
return RedirectToAction("mergeletterttofiles123", "managefile", new { dropdownItems, SeatId = seatId });
// 2nd controller action
public ActionResult mergeletterttofiles123(List<SelectListItem> dropdownItems, int SeatId, string msg)
{
// dropdownItems shows null( 0 count)
}
As an option you can store list in Session:
...........
//your code
Session["dropdownItems"]=dropdownItems;
RedirectToAction("mergeletterttofiles123", "managefile", new { SeatId = seatId });
And then:
public ActionResult mergeletterttofiles123(int SeatId, string msg)
{
//then get it using something like
var dropdownItems = Session["dropdownItems"] as List<SelectListItem>;
}
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
I'm using Web Api to build a ViewModel based on the Enum. This view model will be sending id and the name. Basically I want to use this viewModel to use dropdownList.
Here is my code: works fine but I don't want to use ListItem in Web Api.
// GET api/values
public List<DropdownViewModel> Get()
{
List<DropdownViewModel> ddlList = new List<DropdownViewModel>();
foreach (int r in Enum.GetValues(typeof(CountryEnum)))
{
ListItem item = new ListItem(Enum.GetName(typeof(CountryEnum), r), r.ToString());
ddlList.Add(new DropdownViewModel
{
id = item.Value,
name = item.Text
});
}
return ddlList;
}
Can anyone re-factor this code without using ListItem?
The Linq Select method should work.
Edit: That just goes to show that if it's not tested it doesn't work. This is tested. It should work.
public List<DropdownViewModel> Get()
{
return Enum.GetValues(typeof (CountryEnum)).Cast<int>()
.Select(id => new DropdownViewModel
{
id = id,
name = Enum.GetName(typeof (CountryEnum), id)
}).ToList();
}
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.