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)
Related
Ok, I'm trying to do a proper dropdown in Core 3.1. In this example https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1#the-select-tag-helper
Model has a new list with hardcoded values
public string Country { get; set; }
public List<SelectListItem> Countries { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "MX", Text = "Mexico" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "US", Text = "USA" },
};
I looked for examples where the list is coming from the database but they are very inconsistent. The only way I was able to do the dropdown list is with the ViewBag which is not advised.
I have two models. 1.
public partial class Glossary
{
public int UniqueId { get; set; }
public int Category { get; set; }
public string DisplayText { get; set; }
}
which is my view model
public partial class AdminUser
{
[Key]
public int Id { get; set; }
public string UserName { get; set; }
public string UserLocation { get; set; }
public string UserStatus { get; set; }
//public IEnumerable<Glossary> Glossary { get; set; } //I used this for ViewBag
public List<SelectListItem> UserLocations { get; } = new List<SelectListItem>
{
according to the example my query should go here
};
}
Here is my controller:
public IActionResult Create()
{
// This is the ViewBag that worked with HTML helpers, but I'm trying to use tag-helpers.
/*IEnumerable<SelectListItem> LocationsList = _context.Glossary.Where(x => x.Category == 1).Select(x => new SelectListItem
{
Value = x.UniqueId.ToString(),
Text = x.DisplayText
});
ViewBag.LocationsList = LocationsList;
*/
return View();
}
All examples that found were hardcoded lists and nothing with getting it from the database. What is the proper way to get the data from the Glossary table through the view model with ViewBag? Any pointers are appreciated.
ALSO:
When using this example: Select Tag Helper in ASP.NET Core MVC
When I used
public SelectList Employees { set; get; }
I got error: InvalidOperationException: The entity type 'SelectListGroup' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.
Both of my tables have PK and adding [Key] to Glossary model didn't fix it.
If you'd like to retrieve data from db and populate a dropdown with retrieved data through a view model (or ViewBag), you can refer to following code snippet.
In AdminUser view model class, include these properties
public string Selected_Glossary { get; set; }
public List<SelectListItem> Glossary_List { get; set; }
In controller
public IActionResult Create(AdminUser model)
{
var adminuser_model = new AdminUser
{
UserName="test"
//for other properties
};
//retrieve data from Glossary table
var items = _context.Glossary.Where(x => x.Category == 1).Select(x => new SelectListItem
{
Value = x.UniqueId.ToString(),
Text = x.DisplayText
}).ToList();
//pass dropdown items through a view model
adminuser_model.Glossary_List = items;
////pass dropdown items through ViewBag
//ViewBag.Glossary_List = items;
return View(adminuser_model);
}
In view page
#model AdminUser
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<form asp-controller="Home" asp-action="Create" method="post">
<select asp-for="Selected_Glossary" asp-items="Model.Glossary_List"></select>
#*populate it through ViewBag*#
#*<select asp-for="Selected_Glossary" asp-items="ViewBag.Glossary_List"></select>*#
<input type="submit" value="Submit" />
</form>
Test Result
I'm not sure what I'm doing wrong. I have a model with a SelectList property that will contain multiple dates as its values. I want to display these values without the timestamp added. How can I show these dates in shortdatetime format? I have the following ViewModel:
public class EditWeightsViewModel
{
[DisplayName("Associates")]
public SelectList AssociatesList { get; set; }
[DisplayName("Week")]
public SelectList WeeksOfEntryList { get; set; }
public decimal Weight { get; set; }
}
Here's part of my controller (*Note, weeks is a List of DateTimes):
editWeightsViewModel.WeeksOfEntryList = new SelectList(weeks.Select(item => new SelectListItem
{
Selected = false,
Value = item.ToString(),
Text = item.ToShortDateString()
}));
My dropdownlist is showing System.Web.MVC.SelectListItem instead of the actual dates. What am I doing wrong? Am I wrong to go about it this way? Would it be easier to create an editor template that displays this in ShortDateTime format?
Html.DropDownListFor helper method's second argument is a collection of SelectListItem. So change the type of WeeksOfEntryList property to a list of SelectListItem. I also added another property, SelectedWeek to store the selected option value.
public class EditWeightsViewModel
{
public string SelectedWeek {set;get;}
[DisplayName("Week")]
public List<SelectListItem> WeeksOfEntryList { get; set; }
[DisplayName("Associates")]
public SelectList AssociatesList { get; set; }
public decimal Weight { get; set; }
}
And when you load the WeeksOfEntryList property value of your viewmodel.
public ActionResult Create()
{
var vm = new EditWeightsViewModel();
vm.WeeksOfEntryList = weeks.Select(s=> new SelectListItem
{ Value=s.ToShortDateString(),
Text=s.ToShortDateString()}).ToList();
//If you want to keep one option selected, Set the vm.SelectedWeek property value.
return View(vm);
}
And in your razor view,
#using YourNameSpaceHere.EditWeightsViewModel
#Html.DropDownListFor(s=>s.SelectedWeek, Model.WeeksOfEntryList ,"Select")
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.
I have an MVC webpage with a DropDownList full of items.
Every item is an object from my Database that represent a file on disk.
My object class:
namespace CapturesMVC.Models
public class Capture : IEquatable<Capture>
{
public int id { get; set; }
[Display(Name = "File Name")]
public string fileName { get; set; }
[Display(Name = "Browser")]
public string browser { get; set; }
[Display(Name = "Mobile")]
public string mobile { get; set; }
[Display(Name = "Protocol")]
public string protocol_site { get; set; }
public string family { get; set; }
public sealed override bool Equals(object other)
{
return Equals(other as Capture);
}
public bool Equals(Capture other)
{
if (other == null)
{
return false;
}
else
{
return this.protocol_site == other.protocol_site;
}
}
public override int GetHashCode()
{
return protocol_site.GetHashCode();
}
}
CaptureDBContext class:
namespace CapturesMVC.Models
public class CaptureDBContext : DbContext
{
public DbSet<Capture> Captures { get; set; }
}
This is my controller:
[HttpPost]
public ActionResult Index(string File)
{
var list = db.Captures.Where(x => x.protocol== File).ToArray();
ViewBag.Files = list;
return View();
}
Index.cshtml:
#using (Html.BeginForm())
{
<div>
#Html.DropDownList("File", new SelectList(ViewBag.Files, "protocol_site", "protocol_site"), "Select webmail site", new { style = "vertical-align:middle;" })
<button type="submit">Select</button>
</div>
}
</body>
After choosing an item from my DropDownList and hitting the button, the Index action is executed and returns list of objects that match one of my object properties and this list I want to show over my webpage inside a list, but the current situation is that this list is inserted into my DropDownList.
You want to implement Cascading DropDownList
check this example 'Cascading DropDownList in ASP.Net MVC' on msdn code or this on c-sharpcorner
The problem is that you put the objects in the same ViewBag property that your Dropdownlist gets its values from.
You could make a List and put that in your ViewBag:
List<Capture> list = db.Captures.Where(x => x.protocol== File).ToList();
ViewBag.data = list;
And enumerate over these and display some html in your view (within an unordered list for example). But you have to cast it back to a list first:
#using Namespace.Capture
...
<ul>
foreach (var item in (ViewBag.data as List<Capture>))
{
<li>#item.Property</li>
}
</ul>
ViewBag is a C# 4 dynamic type. You need to cast the entities from it to use them in a type-safe way.
But I would recommend using a view model with the list as a property and sending that to the view from your controller action.
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();
}