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" })
Related
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 })
Below is my Controller that outputs a List to Partial view. My Question is how do I render the ActionResult output as a dropdown. ( I do not want to use ViewBag Please )
using System.Web.Mvc;
namespace CMS.Controllers
{
public class ArticleTypeController : Controller
{
// GET: ArticleType
[ChildActionOnly]
public ActionResult Get(int _siteId)
{
using (var ctx = new CMSEntities())
{
List<articleType> listArticleType = CMS.Models.Cms.getArticleTypes(CMS.Models.Cms.getSiteId()).ToList();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var item in listArticleType)
{
items.Add(new SelectListItem { Value = item.id.Value.ToString(), Text = item.name });
}
items.Add(new SelectListItem { Value = "0", Text = "--Select--", Selected=true });
return PartialView(items);
}
}
}
}
View looks like below:
#model List<SelectListItem>
<h2>test</h2>
If you have a model property to which you're trying to bind the selected value, you can pass a lambda expression to indicate the property that you want to bind and the framework will generate the appropriate name:
#Html.DropDownList(m => m.FinancialYearID, MySelectList,
"Select option", new { #class= "foo" ,data-somename="dataName"})
your partial view should have only this dropdown and you can render this partial view any where you want using following Jquery function
renderPartialInDiv("partial view url","div id or class")
Hi I have Dropdown in Index page where user needs to select lists. Values are coming from Database. I took this dropdown value into session so I can carry this to Httppost.
Below is my code in Index page :
var activitydropdown = orderdata.uspApp_ActivityPageReportname(Convert.ToInt32(newid)).ToList();
List<SelectListItem> activitypage = new List<SelectListItem>();
if (activitydropdown != null && activitydropdown.Count > 0)
{
foreach (var activityresults in activitydropdown)
{
activitypage.Add(new SelectListItem
{
Text = activityresults.name,
Value = activityresults.id.ToString(),
});
}
}
ViewData["activitydropdown"] = activitypage;
Session["activitydropdown"] = activitypage;
And this is my code in view :
#using (Html.BeginForm("Index", "Automation", new { step = "2" }, FormMethod.Post, new { id = "frmIndex" }))
{
#Html.DropDownList("DrpaActivity", ViewData["activitydropdown"] as List<SelectListItem>, "All", new { style = "margin-left:694px;margin-bottom:20px;", onchange = "submit();" })
Now when user selects list from dropdown, i need to carry that text to my httpost index. Now in httpost index, in debug mode if i see this code :
var sessionlistautomation = Session["activitydropdown"];
I can see text and value and selected is false for every item. So how can i carry text here selected from Index to httpost, so when user selects list from dropdown, it stores that text value.
It will be available in your Request i.e.
Request["DrpaActivity"]
However I would strongly advise using ViewModels instead as they're typesafe, less room for error and easier to use.
If you create a view model, like below:
public class AViewModel
{
public string DrpaActivity { get; set; }
public List<SelectListItem> ActivitySelectList { get; set; }
}
In your Index you can return it like this:
public ActionResult Index()
{
var model = new AViewModel();
// set the select list i.e.
model.ActivitySelectList = // get from db etc
return View(model);
}
Then in your view declare the model at the top
#model AViewModel
...
Set your dropdown like this:
#Html.DropDownListFor(m => m.DrpaActivity, Model.ActivitySelectList as List<SelectListItem>, "All", new { style = "margin-left:694px;margin-bottom:20px;", onchange = "submit();" })
You can then get your selected drop-down in your post as follows:
[HttpPost]
public ActionResult Index(AViewModel model)
{
var isValid = model.DrpaActivity;
return View(model);
}
I want to select the default value in drop down list where policyId = 7 but it didn't select that value, what i am doing wrong?
Controller:
var pm = new ManagerClass();
IEnumerable<myClass> po = pm.GetDataFromDb();
IEnumerable<SelectListItem> Policies = new SelectList(po, "PolicyID", "PolicyName", new { PolicyID = 7 });
ViewBag.Policies = Policies;
View:
#Html.DropDownListFor(m => m.PolicyID, ViewBag.Policies as IEnumerable<SelectListItem>, new { #class = "dropdown-field"})
It's because it's not actually selecting the value in the SelectList.
First, to make it nicer, put the items in your view model to prevent the cast (this is better practice too):
public class MyModel
{
public int PolicyID { get; set; }
public List<SelectListItem> Policies { get; set; }
//rest of your model
}
Then populate it:
var model = new MyModel();
model.Policies = po
.Select(p => new SelectListItem
{
Text = p.PolicyName,
Value = p.PolicyID.ToString(),
Selected = p.PolicyID == currentPolicyId //change that to whatever current is
})
.ToList();
Then in your view, do:
#Html.DropDownListFor(m => m.PolicyID, Model.Policies, new { #class = "dropdown-field"})
Just set the PolicyID property on your view model to the value you want to be preselected:
var pm = new ManagerClass();
var po = pm.GetDataFromDb();
ViewBag.Policies = new SelectList(po, "PolicyID", "PolicyName");
viewModel.PolicyID = 7;
return View(viewModel);
Since your DropDownList is bound to the PolicyID property (m => m.PolicyID), then its value will be used when deciding which element to be preselected.
In case that you have a static menu:
1- create the following class:
public static class StaticMenus
{
public static List<string> GetGridRowsCount()
{
List<string> result = new List<string>();
result.Add("3");
result.Add("5");
result.Add("10");
result.Add("20");
result.Add("25");
result.Add("50");
result.Add("100");
return result;
}
}
2- add the following code to your controller :
ViewData["CountryList"] = new SelectList(StaticMenus.GetGridRowsCount(),"10");
3- add the following code to your view:
#Html.DropDownList("MainGridRowsCount", ViewData["RowsCountList"] as SelectList)
How do I set the selected value on a drop down list? Here is what I have so far:
#model Web.Models.PostGraduateModels.PlannedSpecialty
#Html.DropDownList("PlannedSpecialtyID")
//controller
[HttpGet]
public PartialViewResult PlannedSpecialty()
{
// Get Planned Specialty ID
var pgtservice = new PgtService();
PostGraduateModels.PlannedSpecialty plannedSpecialty = pgtservice.GetPlannedSpecialtyId();
// Get Data for Planned Specialty DropDown List from SpecialtyLookup
var pgtServ = new PgtService();
var items = pgtServ.GetPlannedSpecialtyDropDownItems();
ViewBag.PlannedSpecialtyId = items;
return PartialView(plannedSpecialty);
}
// service
public IEnumerable<SelectListItem> GetPlannedSpecialtyDropDownItems ()
{
using (var db = Step3Provider.CreateInstance())
{
var specialtyList = db.GetPlannedSpecialtyDdlItems();
return specialtyList;
}
}
// data access
public IEnumerable<SelectListItem> GetPlannedSpecialtyDdlItems()
{
IEnumerable<Specialty> specialties = this._context.Specialties().GetAll();
var selList = new List<SelectListItem>();
foreach (var item in specialties)
{
var tempps = new SelectListItem()
{
Text = item.Description,
Value = item.Id.ToString()
};
selList.Add(tempps);
}
return selList;
}
I would recommend you to avoid using ViewBag/ViewData/ Weekly typed code. Use strongly typed code and it makes it more readable. Do not use the Magic strings/ Magic variables. I would add a collection property to your ViewModel to hold the SelectList items and another property to hold the selected item value.
public class PlannedSpecialty
{
public IEnumerable<SelectListItem> SpecialtyItems { set;get;}
public int SelectedSpeciality { set;get;}
//Other Properties
}
and in your Get action, If you want to set some Item as selected,
public PartialViewResult PlannedSpecialty()
{
var pgtServ = new PgtService();
var vm=new PlannedSpecialty();
vm.SpecialtyItems = pgtServ.GetPlannedSpecialtyDropDownItems();
//just hard coding for demo. you may get the value from some source.
vm.SelectedSpeciality=25;// here you are setting the selected value.
return View(vm);
}
Now in the View, use the Html.DropDownListFor helper method
#Html.DropDownListFor(x=>x.SelectedSpeciality,Model.SpecialtyItems,"select one ")
Use the selected property of the SelectListItem class:
selList.Selected = true;