I'm using MVC where I have a list of strings that I would like to point to a new page. I'm using Razor and am very new to MVC and cannot seem to find the answer to my question through google.
My list could contain of the following:
"hello"
"goodbye"
"seeya"
I know how to insert strings from the controller to the html page using ViewBag, and I would use the following actionlink if I had a fixed set of strings:
#Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "hello" })
#Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "goodbye" })
#Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "seeya" })
As I understand it, this would generate 3 links that would redirect to the subpage "ChemicalClass", and it would contain the one of the 3 parameters, depending on the link that was clicked.
My quesiton is, how can I do the same, but have the ActionLinks created dynamically, since I won't know how many links are going to be created, nor the content of the strings. My goal is to show these links on the webpage in (preferabely) a list form, e.g.:
<ol>
<li>
hello
</li>
<li>
goodbye
</li>
<li>
seeya
</li>
</ol>
Where each element in the list is a link and not just a string.
Create a view model that stores a collection of links
Model
public class ViewModel
{
public IList<string> Links { get; set; }
}
populate that model in your controller
Controller
public ActionResult Index()
{
var model = new ViewModel
{
Links = new List<string>
{
"Hello",
"Goodbye",
"Seeya"
}
};
return View(model);
}
and finally your view
View
#model MvcApplication1.Models.ViewModel
<ol>
#foreach (var item in Model.Links)
{
<li>
#Html.ActionLink("viewedName", "ChemicalClass", new { mystring = item })
</li>
}
</ol>
Your class holds your collection of strings and razor loops over them to produce your links.
you can use something like this.
<ul>
#foreach (var x in Model)
{
<li>#x.myString </li>
}
</ul>
I have something like this in one of my Views:
#foreach (var item in Model.MyList)
{
<li>
#Html.ActionLink("Select", "ActionName", "Chemical", new {id = item.AdmNum}, new { #class = "label label-info"})
</li>
}
Related
Getting data in a list format using IEnumerable,How to return to View page from controller.
model.Name = UserPermissions.Name; is this correct format?
List containing name,Id,Amount,Currency for each plan.
model.Name = UserPermissions.Name; getting error here.from list pass all data to view dynamically in DIV.How to pass data and display in view.help me guys
public ActionResult Plans(Plan model)
{
var planServicenew = new StripePlanService(apiKey);
IEnumerable<StripePlan> responsenew = planServicenew.List();
foreach (var UserPermissions in responsenew)
{
model.Name = UserPermissions.Name;
}
return View(model);
}
view page
#model IEnumerable<ABACUS.Models.Plan>
#foreach (var item in Model)
{
<div class="plan">
<h3 class="plan-title">#Html.DisplayFor(modelItem => item.Name)</h3>
<p class="plan-price">#Html.DisplayFor(modelItem => item.Currency)#Html.DisplayFor(modelItem => item.Amount) <span class="plan-unit">per month</span></p>
<ul class="plan-features">
<li class="plan-feature">#Html.DisplayFor(modelItem => item.Trial)-days <span class="plan-feature-name">Trial</span></li>
</ul>
Choose Plan
</div>
}
Considering you have "Plan" model and you want to pass the list of Plans to your view,
try below way to resolve your issue -
var planServicenew = new StripePlanService(apiKey);
IEnumerable<StripePlan> responsenew = planServicenew.List();
var plans = (from r in responsenew
select new Plan
{
Name = r.Name,
Currency = r.Currency,
Amount = r.Amount,
Trial = r.Trial
}).ToList() as List<Plan>;
return View(plans);
I have the following problem: I am making an MVC intranet website for the corporation I'm working for. One part of the job is to make a phonebook - I need a tree like structure of the departments (with depth).
I have a view with two div elements - left (containing the departments, the structure follows below), and a right div which should show all the employees that are working in the selected (clicked) department.
#helper GetTree(List<PhonesClasses.Department> department, int parentID){
foreach(var i in department.Where(a=>a.headDepartmentID.Equals(parentID)))
{
{var childDepartments = department.Where(a => a.headDepartmentID.Equals(i.departmentID)).Count();
if(childDepartments > 0)
{
<li class="haschlid" id="#i.departmentID">
#i.departmentName
<ul class="sub-dep">
#GetTree(department, #i.departmentID)
</ul>
</li>
}
else
{
<li id="#i.departmentID">
#i.departmentName
</li>
}
}
}
The following is the above-mentioned view. As you can see, I had the idea to make a partial view but I'm not sure I'm headed in the right direction.
<div class ="containerStructure">
<div class="leftDivStructure">
#if (Model != null && Model.Count() > 0)
{
<ul class="list" id="deplist">
#Treeview.GetTree(Model, Model.FirstOrDefault().headDepartmentID)
</ul>
}
</div>
<div class="rightDivStructure">
Employee
#*#Html.Partial("_PeopleInDepartment", new {depID = Model.departmentID()})*#
</div>
</div>
My employee and department classes both have DepartmentID fields, so when a department is clicked on in my tree view, a parameter () should be passed to the partial view, or whatever needs to be there to handle the parameter and show the employees. Below is the controller that I think has to fetch the result.
public ActionResult PeopleInDepartment(int depID)
{
List<Person> peopleList = new List<Person>();
peopleList = Persons.GetPersons(depID);
return View(peopleList);
}
For further clarifications please comment!
View:
#model dynamic
<div class="btn-group">
<a class="btn btn-default dropdown-toggle btn-select" data-toggle="dropdown" href="#">Select a Country <span class="caret"></span></a>
<ul class="dropdown-menu">
#foreach (dynamic m in Model)
{
<li>"#m.EmployeeName"</li>
}
</ul>
</div>
Controller :
public ActionResult Index()
{
var Employees = Connections.SaleBranch.SqlConn.Query("SELECT EmployeeName,EmployeeID FROM dbo.udft_Employee(#RunDate) WHERE OfficerEmployeeID=#OfficerEmployeeID",
new { OfficerEmployeeID = 78273, RunDate = DateTime.Now.GetPersianDate() },
commandType: CommandType.Text).ToList();
var EmployeesList = Employees.Select(x => new { EmployeeName = x.EmployeeName, EmployeeID = x.EmployeeID }).ToList();
return View("Point/Index", EmployeesList);
}
The object m shows 2 properties(EmployeeName,EmployeeID).
But can't fetch m.EmployeeName value
Try get desired value via reflection:
#foreach (dynamic m in Model)
{
var EmployeeName = m.GetType().GetProperty("EmployeeName").GetValue(m);
<li>"#EmployeeName"</li>
}
That's because the objects in employeesList are not dynamic but are anonymous objects. Anonymous can't be used outside the scope they are created in.
A dynamic view model is not a good idea, but if you insist, you can look here. Instead I would make a strongly typed model for the view.
I have multiple methods that return either a simple type (string, ..) & methods that return collections Collection<Tuple<Model_name, string>>
I tried with a simple Collection<string> at first but when i used a Tempdata to pass the collection to the view it doesn't work.
Example :
Controller:
public ActionResult Index()
{
Collection<string> test_Q_Q = new Collection<string>();
test_Q_Q.add("abcd");
test_Q_Q.add("adbc");
Tempdata["test"] = test_Q_Q;
return view();
}
View:
<!--Bla Bla here-->
#foreach (var lst in Tempdata["test"]) //error here
{
<li> </li>
}
The real issue is that TempData is a stupid dictionary, and doesn't know that there's an IEnumerable stored in it's data. If you really wanted to stick with this approach, simply cast the TempData to the appropriate type, like so:
#foreach (var lst in (Collection<string>) TempData["test"])
{
<li> #lst </li>
}
Having said that, I don't think you should be using TempData. What I recommend is using a strongly typed Model object that gets passed into the view, something like this in the controller:
var model = new MyCustomType();
model.ListOfStrings = new Collection<string>();
model.ListOfStrings.Add("foo");
model.ListOfStrings.Add("blah"); // You get the idea
return View(model);
Then, in your view declare the type like so at the top:
#model MyCustomType
And address it like this:
#foreach (var item in Model.ListOfStrings)
{
<li> #item </li>
}
At the very least, I hope you would use ViewBag instead of TempData. As some of the comments have mentioned, TempData has a particular use, having to do with the lifetime of the HTTP request, and is not meant to be used the way you're using it. Good Luck!
Try closing your foreach loop test.
<!--Bla Bla here-->
#foreach (var lst in Tempdata["test"] ) // Close
{
<li> ???? </li>
}
Here is what my view looks like:
#model Affiliate
<div class="box paint color_16">
<div class="title">
<h4><i class="icon-tasks"></i><span>#Model.CompanyName's Commissions</span> </h4>
</div>
<div class="content top ">
<div class="subtitle">
#Html.ActionLink("Void", "DeleteInvoice", new { commList = "??", affId = Model.Id }, new { #class = "btn" })
#Html.ActionLink("Create Invoice", "CreateInvoice", new { commList = "??", affId = Model.Id }, new { #class = "btn" })
#Html.ActionLink("Pay", "PayInvoice", new { commList = "??", affId = Model.Id }, new { #class = "btn" })
</div>
<table class="table table-striped table-hover">
<tr>
<h3>Commissions</h3>
</tr>
<tr>
<td></td>
<td>Amount</td>
<td>Status</td>
<td>Action</td>
</tr>
#foreach (var item in Model.Commissions)
{
<tr>
#if (item.Status == ViewBag.PaymentStatus || ViewBag.PaymentStatus == "All")
{
<td>#Html.CheckBox("commId", new { value = item.Id })</td>
<td>#Html.DisplayFor(x => item.PayoutAmount)</td>
<td>#Html.DisplayFor(x => item.Status)</td>
}
</tr>
}
</table>
</div>
What I want to be able to do is when I hit an actionlink on the top, grab all the items from the table that are checked, and pass that list of id's to the controller logic. I am assuming a viewmodel may be the solution, something like this:
public Affiliate affilite { get; set; }
public List<int> selectedItems { get; set; }
etc.
But how to I get the selected Items into that VM selectedItems container?
Based off your comments, you don't seem to be looking for the most "correct" answer, but rather just a quick and dirty "how would I do this" answer. If you just want to pass the list, you could setup your controller action like this:
public ActionResult MyAction(int[] id)
{
...
}
Or, you seem to indicate it is strongly typed to a view model with a property that contains a List (I would shorten the name of the property, you'll see why in a second).
In javascript, the easiest thing to do would be to use jQuery to bind a click event on your hyperlink that gets the list of items that are checked and appends that to the query string.
$("#myLink").click(function()
{
var url = "site.com/action?";
var ids = $(".table").find("input:checked");
ids.each(function()
{
url += "id=" + $(this).val() + "&"
});
window.location = url;
});
Basically, you want to create one long query string with the action parameter's name repeated over and over, which identifies an array. It looks something like this (id is for int[] id in MyAction):
id=15&id=20&id=25&id=30&....
And then once the query string is built, redirect the user to that url. MVC should then be able to bind that to an array and you're all set.
That's basically the idea, anyway; the syntax and the javascript I wrote could be way off so don't copy my code and expect it to work as is - I wrote that off the top of my head. If your action is bound to a viewmodel, then you need to set the parameter in the query string to the name of the property of your model:
selectedids=1&selectedids=2&selectedids=3...
Or, if the array is a property of an object, which is a property of the model...
model.selectedids=1&model.selectedids=2&model.selectedids=3...
You'll just need to play around with it some.
Use html checks inside form tag ( you could use helpers too) and post the model to a post action.
MVC will serialize the model automatically