DropDownList show the whole object instead of object property - c#

I have DropDownList that read fils from my database and show this files in my DropDownList.
The current solution is show on my DropDownListItem System.Web.Mvc.SelectList instead of my Object property. I want to include a drop down list of my object (read from database) across my webpage.
This is my object:
public class MyObject
{
public int id { get; set; }
public string fileName { get; set; }
public string browser { get; set; }
public string protocol { get; set; }
public string family { get; set; }
}
My controller:
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
ViewBag.Files = lList;
return View();
}
Index.cshtml
#Html.DropDownList("File",new SelectList(ViewBag.Files))
What i want to see in my DropDownList is my protocol property.

Try like this:
#Html.DropDownList("File", new SelectList(ViewBag.Files, "id", "fileName"))

Try this
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").DistinctBy(x=> x.protocol).ToList();
ViewBag.Files = new SelectList(list,"Id","protocol");
return View();
}

Related

Creating dropdownlist from database with Entity Framework Core in an ASP.NET Core 5 MVC application

In my app I'm trying to populate a drop-down menu by taking data from the db with EF Core, but unfortunately I've been trying it for two days without success.
I have tried to do this as recommended in this post, but I keep getting errors.
More specifically the error I'm facing now is
'IEnumerable' does not contain a definition for 'Years' and no accessible extension method 'Years' accepting a first argument of type 'IEnumerable' could be found
This error comes from the view:
#Html.DropDownList(m => m.Years, Model.Years, "-- Select year --")
Here is my model class:
public partial class Bdgfixmonth
{
public int Counter { get; set; }
public int Byear { get; set; }
//
public IEnumerable<SelectListItem> Years { get; set; }
public string Bbudget { get; set; }
public int Bmonth { get; set; }
public string Blongmonth { get; set; }
public int Closed { get; set; }
public string Current { get; set; }
}
And here is my controller for the GET action method Index:
private readonly salesContext _context;
public IEnumerable<SelectListItem> Years { get; set; }
public bdgfixmonthController(salesContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var bdgfixmonths = await _context.Bdgfixmonths.ToListAsync();
IEnumerable<SelectListItem> GetAllYears()
{
IEnumerable<SelectListItem> list = _context.Bdgfixmonths
.AsEnumerable()
.Select(s => new SelectListItem
{
Selected = false,
Text = s.Byear.ToString(),
Value = s.Byear.ToString()
});
return list;
}
Years = GetAllYears();
return View(bdgfixmonths);
}
The goal here is to populate the drop-down menu with the data of the db, and then make a query based on the selected value, so that only the relevant values are shown (in this case based on the year).
Any help would be very appreciated, thanks.
Since you're returning a model that contains a list of Bdgfixmonths, it's probably better to create a view model that looks like this:
public class BdgfixmonthsViewModel
{
public List<Bdgfixmonth> Bdgfixmonths { get; set; }
public IEnumerable<SelectListItem> Years { get; set; }
}
Then, your Action Method will change to:
private readonly salesContext _context;
public bdgfixmonthController(salesContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var vm = new BdgfixmonthsViewModel();
var bdgfixmonths = await _context.Bdgfixmonths.ToListAsync();
IEnumerable<SelectListItem> GetAllYears()
{
IEnumerable<SelectListItem> list = _context.Bdgfixmonths
.AsEnumerable()
.Select(s => new SelectListItem
{
Selected = false,
Text = s.Byear.ToString(),
Value = s.Byear.ToString()
});
return list;
}
vm.Years = GetAllYears();
vm.Bdgfixmonths = bdgfixmonths;
return View(vm);
}
Your ViewModel will have the two collections which can then be used in the view. You will need to update the View to reference the Bdgfixmonth properties like Bdgfixmonths.Bbudget for example. Also, the model will change to something like:
#model IEnumerable<Bdgfixmonth>
becomes
#model BdgfixmonthsViewModel
And then any iteration code will change to:
#foreach (var item in Model.Bdgfixmonths)
{
item.Bbudget
}

Assign one model value to another

I have a model DropDownConfiguration which is fetching values from database and populating the dropdown list.
Model:
public class DropDownConfiguration
{
public int ID { get; set; }
public int Quarter { get; set; }
public int Year { get; set; }
public string Project { get; set; }
public string LineID { get; set; }
}
html:
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "ID", "Project"), "-- Select Project --", new { required = true, #class = "form-control" })
I have another model DetailsConfiguration which has all the fields which need be saved into the database.
public class DetailsConfiguration
{
public int Quarter { get; set; }
public int Year { get; set; }
public string Project { get; set; }
public string ItemModel { get; set; }
}
Controller HttpPost:
[ActionName("DetailsForm")]
[HttpPost]
public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
{
DetailsConfiguration detailsConfig = new DetailsConfiguration();
detailsConfig.Quarter = Convert.ToInt32(form["Quarter"]);
detailsConfig.Year = Convert.ToInt32(form["Year"]);
detailsConfig.Project = model.detailsConfig.Project;
detailsConfig.ItemModel = model.detailsConfig.ItemModel;
detailsConfig.LineID = model.detailsConfig.LineID;
floorService.SaveDetails(detailsConfig);
ModelState.Clear();
ViewBag.message = "Success";
return View("DetailsForm");
}
Is there anyway to do something like:
model.detailsConfig.Project = model.dropConfig.Project
I need the selection of Project to be posted back to database through DetailsConfiguration.
You could create a mapper which sets the values of the properties in DropDownConfiguration to DetailsConfiguration.
When you change the dropdown you send the selected DropDownConfiguration to the server. You know exactly what properties you can expect here so you can do something like this:
[HttpPost]
public IHttpActionResult AddDetailsConfiguration(DropDownConfiguration parameter)
{
//check here if values in parameter are set
var detailsConfiguration = new DetailsConfiguration {
Quarter = parameter.Quarter,
Year = parameter.Year,
Project = parameter.Project
}
//Insert detailsConfiguration to database
Return Ok();
}
Note that you have to make sure you send a DropDownConfiguration object on selecting a dropdown item. You could also only send the values you need like this:
[HttpPost]
public IHttpActionResult AddDetailsConfiguration(int quarter, int year, string project)
{
//Check here if values in parameter are set and if values are correct
var detailsConfiguration = new DetailsConfiguration
{
Quarter = quarter,
Year = year,
Project = project
}
//Insert detailsConfiguration to database
Return Ok();
}

substring one field on model and send to view

i have a model and i send substring one field on this model and return to a view for show in gridview
my model is:
public class News
{
public int ID { get; set; }
[MaxLength(300)]
public string Title { get; set; }
[DataType(DataType.MultilineText)]
[MaxLength]
public string Content { get; set; }
[ReadOnly(true)]
public DateTime Date { get; set; }
[Column("PictureID")]
public virtual Picture Picture { get; set; }
//public IList<Picture> PicID { get; set; }
[Column("NewsTypeID",Order=1)]
public virtual NewsType NewsType { get; set; }
public ICollection<Tag> Tags { get; set; }
public News()
{
Tags = new List<Tag>();
}
}
when i send this model by myController:
public ActionResult ShowNews()
{
var data = new DatabaseContext();
var news = data.newsInfo.ToList();
return View(news);
}
it is ok and show properly in gridview
but if send this model by this cod in controller:
public ActionResult ShowNews()
{
var data = new DatabaseContext();
var news = data.newsInfo.Select(x => new { Content = x.Content.Substring(0,200), x }).ToList();
return View(news);
}
show this Error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType02[System.String,NewsAgency.Models.News]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[NewsAgency.Models.News]'.
i have send substring one of the field
what is problem?
You have created list of anonymous objects in this statement:
data.newsInfo.Select(x => new { Content = x.Content.Substring(0,200), x }).ToList();
And you have send it as model to your view:
View(news);
But, in your view you have set model type as List<News>. So, the exception is throwned. Try to change your code as:
var news = data.newsInfo.AsEnumerable().Select(x => { x.Content = x.Content.Substring(0,200); return x; }).ToList();
If you want to send whole Content values along with substrings, then I recommend to use first way and get the substring of all item's Content with razor inside view.

Populate DropDown using array

I need to populate a dropdown with some data i get from a SOAP server. The server provides me an array of the companies.
How would i use it to populate the DD ?
Here is my User class:
public class Usuario
{
public string Nome { get; set; }
public string Token { get; set; }
public IEnumerable<SelectListItem> Unidades { get; set; }
}
Here is where i receive the companies and send it to the view, i get it from another Action that is redirecting to this Action:
var usuario = TempData["objUsuario"] as UsuarioSSO;
if (usuario == null) return RedirectToAction("Index", "Login");
if (usuario.UsuarioUnidades == null)
{
ModelState.AddModelError("", "Usuário não possui unidades");
return View();
}
var model = new Models.Usuario
{
Unidades = usuario.UsuarioUnidades.ToList().Select(x => new SelectListItem
{
Value = x.CodigoEmitente.ToString(),
Text = x.NomeFantasia
})
};
return View(model);
Here is how i'm trying to display it:
#Html.DropDownListFor(x => x.Unidades, new SelectList(Model.Unidades))
I have already tried of everything but it won't work, i get some conversion errors and when i can make it work it won't display the content, it will only display the object inside the Text area
System.Web.Mvc.SelectListItem
You need to have one property for the selected item and the list of available items, e.g.:
public class Usuario
{
public string Nome { get; set; }
public string Token { get; set; }
public string Unidade { get; set; }
public IEnumerable<SelectListItem> Unidades { get; set; }
}
and then create the drop-down like:
#Html.DropDownListFor(x => x.Unidade, Model.Unidades)
You can directly supply the Unidades as it is already IEnumerable<SelectListItem>.
P.S.: I guessed the singular of Unidades as I do not speak your langauge, whatever it is. I recommend to ALWAYS use english in source code.
Your model needs a value type property to bind the selected option to. If CodigoEmitenteis typeof int then you model property needs to be
public int SelectedUnidades { get; set; }
and you need to assign the SelectList to another property in your view model or to a ViewBag property
ViewBag.UnidadesList = new SelectList(usuario.UsuarioUnidades, "CodigoEmitente", "NomeFantasia");
Then in the view
#Html.DropDownListFor(x => x.SelectedUnidades, (SelectList)ViewBag.UnidadesList)

Fill one property of class by selecting one value on dropdownlist of another model

I have a class Client that have some properties in particular one is restriction_type. Also, I create another class Restriction with an ID and a name properties. The name property correspond to the restriction_type.
Then I display the name of all restrictions in my database in the dropdown list:
#Html.ActionLink("Create New", "Create")
#using (Html.BeginForm("AddRestrictions","Restrictions",FormMethod.Get)){
<p> Type de restriction:
#Html.DropDownList("ClientRestr_type", "All")
</p>
<input type="submit"value="Ajouter"/>
}
That is my controller:
public ActionResult AddRestriction(string ClientRestr_type, Restriction restriction)
{
var RestrLst = new List<string>();
var RestrQry = from d in db.Restrictions
orderby d.name
select d.name;
RestrLst.AddRange(RestrQry.Distinct());
ViewBag.ClientRestr_type = new SelectList(RestrLst);
var clients = from c in db.Restrictions select c;
if (string.IsNullOrEmpty(ClientRestr_type))
return View();
else
{
if (ModelState.IsValid)
{
// Here I have maybe to find the way to solve my problem
}
}
So I want to add the name property of Restriction in the restriction_type property of my Model Client.
Model Client:
public class Client
{
[Required]
public int ID
{
get;
set;
}
[Required]
public string compte
{
get;
set;
}
[Required]
public string portefeuille
{
get;
set;
}
[Required]
public String restriction_type
{
get;
set;
}
[Required]
public Boolean etat
{
get;
set;
}
public Boolean decision
{
get;
set;
}
Model Restriction:
public class Restriction
{
public int restrictionID
{
get;
set;
}
public string name
{
get;
set;
}
}
What do you think about my GetRestrictions() method
private SelectList GetRestrictions()
{
var RestrLst = new List<string>();
var RestrQry = from d in db.Restrictions
orderby d.name
select d.name;
RestrLst.AddRange(RestrQry.Distinct());
return new SelectList(RestrLst);
}
But unfortunately I have an error: Impossible to convert System.Web.Mvc.SelectList to MyApp.Models.Client at line:
model.RestrictionList = GetRestrictions();
I don't understand why
Thank you for your help!
A simplified example:
View model
public class ClientVM
{
public Client Client { get; set; }
public SelectList RestrictionList { get; set; }
}
Controller
[HttpGet]
public ActionResult Create()
{
ClientVM model = new ClientVM();
model.Client = new Client();
model.RestrictionList = GetRestrictions(); // your code to return the select list
return View("Edit", model);
}
[HttpGet]
public ActionResult Edit(int ID)
{
ClientVM model = new ClientVM();
model.Client = // call database to get client based on ID
model.RestrictionList = GetRestrictions();
return View(model);
}
[HttpPost]
public ActionResult Edit(ClientVM model)
{
if (!ModelState.IsValid)
{
model.RestrictionList = GetRestrictions();
return View(model);
}
Client client = model.Client;
// Save and redirect
....
}
View
#model YourNamespace.ClientVM
#using (Html.BeginForm() {
#Html.TextBoxFor(m => m.Client.ID)
#Html.TextBoxFor(m => m.Client.compte)
...
#Html.DropDownListFor(m => m.Client.restriction_type, Model.RestrictionList)
<input type="submit" value="Save" />
}

Categories