Using a model to create a drop down list - c#

Asp.net MVC 4
Entity Framework 5
LINQ
C#
I have a ViewModel I am using already. I am now adding my PermissionType model to my ViewModel.
This model represents a table in the database with the same name.
How do I turn this table into a #Html.DropDownListFor()
From the table for the 'text' I need 'name' from the database.
From the table for the 'value' I need 'ID' from the database.
How do I turn that model into a usable drop down list from my controller to my page?
ForumBoard model = new ForumBoard();
model.TPGForumQuery = db.TPGForums;
model.ProPit_User = db.ProPit_User.Where(m => m.username == userName).FirstOrDefault();
model.TPGForumTopicQuery = db.TPGForumTopics;
// need help here
model.PermissionType = // a list of all of the permission in this table
Edit:
public class ForumBoard
{
public ForumBoard()
{
this.ProPit_User = new ProPit_User();
this.TPGForum = new TPGForum();
this.PermissionType = new List<ListItem>();
}
List<ListItem> PermissionType { get; set; }
public virtual IEnumerable<TPGForum> TPGForumQuery { get; set; }
public virtual ProPit_User ProPit_User { get; set; }
public virtual IEnumerable<TPGForumTopic> TPGForumTopicQuery { get; set; }
public virtual TPGForum TPGForum { get; set; }
}

First, Change your view model
class ForumBoard
{
...
public IEnumerable<ListItem> PermissionType {get; set;}
...
}
Then, assign
ForumBoard model = new ForumBoard();
...
model.PermissionType = db.PermissionType
.Select(p=>
new ListItem (){ Text = p.FieldForText,
Value= p.FieldForValue });
Edit: If your fields are non string type, unfortunately, you have to first call ToList() method.
model.PermissionType = db.PermissionType
//.Select(p => new {Text = p.TextField, Value = p.permissionID })
.ToList()
.Select(p=> new ListItem (){
Text = p.Text.ToString(),
Value= p.Value.ToString()});

You can try this method :
//Controller :
using(MyContext context = new MyContext() )
{
IEnumerable<SelectListItem> listItems = context.PermissionType.Select( p => new SelectListItem{ Text = p.FieldNameFor , Value = p.FieldNameFor });
ViewBag.myList = listItems;
}
/*
Do other stuffs here and then return to View()
*/
// In your view :
#{
IIEnumerable<SelectListItem> listItems = (IEnumerable<SelectListItem>)ViewBag.myList;
}
#Html.DropDownListFor("Name of DropDownList" , listItems )

Related

Choose Default Value from DropDownList

I'm passing in a list of statuses into an Html.DropDownList. I've been searching for a way to choose one of those items as the default, so if the user doesn't change anything, the correct status is passed back to the model. Everything I've found deals with adding an additional value (usually a "null" option) to the list.
How do I default to an already existing item?
Model:
public class ListStatus
{
public string Name { get; set; }
public Guid StatusID { get; set; }
}
public class ViewModel
{
public List<ListStatus> Statuses { get; set; }
}
View:
#Html.DropDownList("StatusID", Model.Statuses.Select(s => new SelectListItem() { Text = s.Name, Value = s.StatusID.ToString() }), new { #class = "medium", required = true })
Sample Data:
'11111111-1111-1111-1111-111111111111': Option 1,
'22222222-2222-2222-2222-222222222222': Default,
'33333333-3333-3333-3333-333333333333': Option 3,
'44444444-4444-4444-4444-444444444444': Option 4
You can add another field to your ViewModel say SelectedStatus and set its value to your desired default. Then you can use #Html.DropDownListFor to display default value.
public class ViewModel
{
public Guid SelectedStatus {get;set;}
public List<ListStatus> Statuses { get; set; }
}
In your controller
[HttpGet]
public ActionResult Index()
{
List<ListStatus> lstStatus = new List<ListStatus>(){
new ListStatus() { Name="X",StatusID = Guid.NewGuid() },
new ListStatus() { Name="Y",StatusID = Guid.NewGuid() },
new ListStatus() { Name="Z",StatusID = Guid.NewGuid() }
};
ViewModel objModel = new ViewModel();
objModel.Statuses = lstStatus;
objModel.SelectedStatus = lstStatus[1].StatusID; // Select whatever you want here to be default.
return View(objModel);
}
In your view
#Html.DropDownListFor(m=>m.SelectedStatus, Model.Statuses.Select(s => new SelectListItem() { Text = s.Name, Value = s.StatusID.ToString() }), new { #class = "medium", required = true })
Here is fiddle : https://dotnetfiddle.net/vTJhaj
If you build a List<SelectListItem> in your controller and pass it back on the view model, you can easily find the one you want selected by default by using the Selected property.
https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem(v=vs.118).aspx
public class ViewModel
{
public List<SelectListItem> Statuses { get; set; }
}
// in controller
ViewModel model = new ViewModel();
// assumes listStatuses is still your ListStatus type.
model.Statuses = listStatuses.Select(s => new SelectListItem() {
Text = s.Name,
Value = s.StatusID.ToString(),
// or whatever your criteria may be.
Selected = s.Name == "22222222-2222-2222-2222-222222222222"
})
Now you don't need to convert to new types in the view, either.

How can i fill a value from one my domain model to my edit model?

In my project i have : countries and CountryEditModel.
public class countries
{
public int id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class CountryEditModel
{
public int id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public bool isvalid{ get;set; }
}
countries is my domain model which is binded with entity framework and countryEditModel is the model which i use in my views.
How can i fill values from countries to countryEditModel. I actually want to bind list of all countries to dropdownlist in my view and I don't want to use my countries domain model directly in my view.
To solve i have done this
var countryDomain = context.Country.Select(c => c).ToList();
var countrylist = new List<CountryEditModel>();
var countrymodel = new CountryEditModel();
foreach (var country in countryDomain)
countrymodel = new CountryEditModel()
{
Code = country.Code,
Name = country.Name,
id = country.id
};
countrylist.Add(countrymodel);
Is there any better way?
Answer:
Actually this is what i exactly wanted to do
var countryViewModel = context.Country.Select(c => new CountryEditModel
{
Code = c.Code,
Name = c.Name,
id = c.id
}).ToList();
As indicated by the #rohitsingh this is what he exactly wanted to do
var countryViewModel = context.Country.Select(c => new CountryEditModel
{
Code = c.Code,
Name = c.Name,
id = c.id
}).ToList();

how to use ICollection for SelectList in Contoller of MVC?

I am developing .NET MVC application.
I want to send the collection of the objects from controller to View using select list.
without using view bag.
ViewModel :
public class AdviceCreateVM
{
public int Id { get; set; }
public string AdviceNo { get; set; }
public ICollection<CompanyVM> Companies { get; set; }
}
public class CompanyVM
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller Code :
public class AdviceCreateController : Controller
{
public ActionResult Create()
{
adviceVM.Companies = new SelectList(ledgerService.GetAll().OrderBy(t => t.Name), "Id", "Name");
}
}
It gives an error -
Cannot implicitly convert type 'System.Web.Mvc.SelectList' to
'System.Collections.Generic.ICollection'. An
explicit conversion exists (are you missing a cast?)
You're trying to assign a SelectList to property of type ICollection<CompanyVM> -- which won't work. You need some like:
var viewModel = new AdviceCreateVM
{
adviceVM.Companies =
ledgerService.GetAll().OrderBy(t => t.Name)
.Select(t=>
new CompanyVM
{
Id = t.Id, // "Id"
Name = t.Name // "Name"
})
.ToList()
};
I'm just guessing on the assignments here, since you didn't specify them.
In the view, you will have to make the select list from Companies property.
#Html.DropDownListFor(model => model.CompanyId,
model.Companies.Select(company =>
new SelectListItem
{
Value = company.Id,
Text = company.Name
}), "--Select Company--")
As indicated in the comments, SelectList does not implement ICollection. Change you view model collection to SelectList
public class AdviceCreateVM
{
public int Id { get; set; }
public string AdviceNo { get; set; }
public SelectList Companies { get; set; } // change to select list
public int CompanyID { get; set; } // for binding the the drop down list
}
Controller
public ActionResult Create()
{
AdviceCreateVM model = new AdviceCreateVM(); // initialise model
model.Companies = new SelectList(ledgerService.GetAll().OrderBy(t => t.Name), "Id", "Name");
}
View
#model YourAssembly.AdviceCreateVM
#using (Html.BeginForm()) {
....
#Html.DropDownFor(m => m.CompanyID, Model.Companies)
...

How to select from two table by id in mvc5

I'm new to MVC5,I had troubles with the problem.
can anybody help me?
I have 2 table, DocMain(Doc_Id,Doc_Title) , DocProduct(Doc_Id,Doc_Content),
I want to select the 2 table content by the same Doc_Id.
And loop them.
Display like:
<ul>
<li>title1content1</li>
<li>title2content2</li>
<li>title3content3</li>
</ul>
....
And how to do it?
//Here is my viewmodel
public class MainProductViewModel
{
public IEnumerable<DocMainListView> DocMainListView { get; set; }
public IEnumerable<DocProductListView> DocProductListView { get; set; }
}
-------------------------------------------------
//Here is my controller
public class DocProductController : Controller
{
private IDocProductRepository repository;
private IDocMainRepository repositoryMain;
public DocProductController(IDocProductRepository docProductRepository, IDocMainRepository docMainRepository)
{
this.repository = docProductRepository;
this.repositoryMain = docMainRepository;
}
public ActionResult List()
{
var products = from docProduct in repository.DocProduct
join docMain in repositoryMain.DocMain
on docProduct.Doc_Id equals docMain.Doc_Id
select new { DocMainTitle = docMain.Doc_Title, DocProductContent = docProduct.DocProduct_Content };
//ViewBag.products = products;
//DocProductListView model = new DocProductListView
//{
// DocProduct = repository.DocProduct
// .Join(repositoryMain.DocMain,
// docProduct => docProduct.Doc_Id,
// docMain => docMain.Doc_Id,
// (docProduct, docMain) => new { a = docMain.Doc_Id, b = docProduct.Doc_Id })
// .OrderByDescending(n => n.)
//};
return View(products);
}
}
I don't know how to write the controller code and View code.
As you want to display the title and content only, so your view model would be
public class MainProductViewModel
{
public IEnumerable<ProductInfo> Products { get; set;}
}
public class ProductInfo
{
public string DocMainTitle { get; set;}
public string DocProductContent { get; set;}
}
And your query would be:
var products = from docProduct in repository.DocProduct
join docMain in repositoryMain.DocMain
on docProduct.Doc_Id equals docMain.Doc_Id
select new ProductInfo { DocMainTitle = docMain.Doc_Title, DocProductContent =
docProduct.DocProduct_Content };
And assign this products to the Products of MainProductViewModel and return to view, then config your view as
#model MainProductViewModel

Populate Result Set in SelectList MVC3

I have following SelectList declaration in CourseRegisterModel:
public class CourseRegisterModel
{
public StudentModel Student { get; set; }
public CourseModel Course { get; set; }
public IEnumerable<SelectListItem> CoursesList { get; set; }
public DateTime RegisterDate { get; set; }
}
In CourseController I am retrieving all available courses by calling wcf web service:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
List<CourseModel> modelList = new List<CourseModel>();
foreach (var serviceCourse in courses)
{
CourseModel model = new CourseModel();
model.CId = serviceCourse.CId;
model.Code = serviceCourse.Code;
model.Name = serviceCourse.Name;
model.Fee = serviceCourse.Fee;
model.Seats = serviceCourse.Seats;
modelList.Add(model);
}
return View(modelList);//RegisterCourses.chtml
}
I need to populate these courses in a dropdown on view RegisterCourses.chtml. How to put all records in selectlist in above code? Also how would i use that selectlist on view?
For starters, your RegisterCourses.cshtml needs to use:
#model <namespace>.CourseRegisterModel
Then, your controller code would be:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
CourseRegisterModel model = new CourseRegisterModel();
//model = other model population here
model.CourseList = courses.Select(sl => new SelectListItem()
{ Text = sl.Name,
Value = sl.CId })
.ToList();
return View(model);
}
And finally, back to your view (RegisterCourses.cshtml) - it should contain:
#Html.DropDownListFor(m => m.Course.CId, Model.CourseList)
Use the Html.DropDownList method: http://msdn.microsoft.com/en-us/library/dd492738(v=vs.108).aspx
Pass in the desired name of the drop down list as first argument, as second argument pass in your CourseList:
#Html.DropDownList("CoursesList", Model.CoursesList)

Categories