How to convert an Enum to ViewModel - c#

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

Related

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

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

Set selected value in dropdown list

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;

Linq using StartsWith always empty

I have a simple List with dummy data as follows:
List<Organisation> list = new List<Organisation>();
list.Add(new Organisation() { LogoUrl = "/images/logos/Blade.png", OrganisationId = 1, OrganisationName = "Blade" });
list.Add(new Organisation() { LogoUrl = "/images/logos/Torn.png", OrganisationId = 2, OrganisationName = "Torn" });
When I run the linq query:
var results = from org in OrganisationsController.GetDummyList()
where org.OrganisationName.StartsWith(searchString)
select org;
It always returns an Empty result. In this case the searchString is specified by the user and the example would be "Tor".
Using different variations like 'where org.OrganisationName == searchString' where the search string is Torn works. But StartsWith never works.
Any ideas where I'm going wrong?
EDIT:
From Jon's code I changed my code to look as follows:
public JsonResult Search(string searchString)
{
//create json result object
JsonResult data = new JsonResult();
var list = OrganisationsController.GetDummyList();
//query the list
var results = from org in list
where org.OrganisationName.ToLower().Contains(searchString.ToLower())
select org;
if (results.Any())
{
System.Diagnostics.Debug.Write("found");
}
//setup the data
data.Data = results;
//return the data
return Json(data, JsonRequestBehavior.AllowGet);
}
Note: I changed the StartsWith to Contains, but both are giving me similary problems.
One of my organisations is called 'Absa'. Here's the really strange thing when I fire up the app for the first time putting in 'bsa' returns nothing, I then enter 'Absa' and it returns a good result. Then I entered 'bsa' again just to double check and it returned Absa which it didn't in the first test. Why would the result not work at first then work later?
Thanks,
Jacques
Unable to reproduce. It works fine for me:
using System;
using System.Collections.Generic;
using System.Linq;
class Organisation
{
public string LogoUrl { get; set; }
// Removed redundant Organisation prefixes
public int Id { get; set; }
public string Name { get; set; }
}
class Test
{
static void Main()
{
// Used collection initializer for sanity
var list = new List<Organisation>
{
new Organisation { LogoUrl = "Blade.png", Id = 1, Name = "Blade" },
new Organisation { LogoUrl = "Torn.png", Id = 2, Name = "Torn" },
};
string searchString = "Tor";
var query = from org in list
where org.Name.StartsWith(searchString)
select org;
// Nicer version:
// var query = list.Where(org => org.Name.StartsWith(searchString));
Console.WriteLine(query.Count()); // 1
}
}
Work out the difference between your code and my code to find out what's wrong.
In particular, you've shown code using List<T>, which means LINQ to Objects. If your real code uses LINQ to SQL or Entity Framework, that could easily affect things.

Categories