Display my Select List Items in ShortDateString format - c#

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")

Related

How to show selected item in Syncfusion DropDownList control

I am working on an ASP.NET MVC application using Syncfusion controls. I have a drop down list in my view. The model has a property "Categories" which is a List of type Category.
public class Category
{
public int XKategorieId { get; set; }
public int? Id { get; set; }
public string Hinweis { get; set; }
public string Kategorie { get; set; }
}
The model of the view also has a property "IdFromCategory". The model is:
public class ReportModel
{
public int? IdFromCategory { get; set; }
public List<Category> Categories { get; set; }
}
I am showing all the categories in the drop down list by setting the "DataSource" of "DropDownList". Now, my issue is that i want to show an item selected in the "DropDownList" when the view loads and that selected item will be the one with "Id" equals to "IdFromCategory ".
#Html.EJS().DropDownList("KundenBetreuung").DataSource(Model.Categories).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Text = "Kategorie", Value = "Id" }).Value(Model.IdFromCategory.ToString()).Width("100%").Render();
This is my code, i am unable to set the selected item in the "DropDownList"
In the Razor code, you have filled the value property with Model.IdFromCategory.ToString() (a string) where the declared properties IdFromCategory and Id both are integers. This mismatching type is the cause of the issue in your end and the value is not being set. To successfully set the value make sure that the value provided is available in the datasource and its type matches as well.
Suggest changing the code as follows
#Html.EJS().DropDownList("KundenBetreuung").DataSource(Model.Categories).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Text = "Kategorie", Value = "Id" }).Value(Model.IdFromCategory).Width("100%").Render();
Check the following example for further reference
Example

How to create view for dropdown?

i have problem with view for dropdown menu. Here is my code.
Model:
public class student
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int StudentId { get; set; }
[Display(Name = "Šifra ispitanika:")]
[Range(1, 9999)]
public int StudentNumber { get; set; }
[Display(Name = "Datum rođenja ispitanika:")]
[DataType(DataType.Date)]
public DateTime DateBirth { get; set; }
[Display(Name = "Mjesto rođenja ispitanika:")]
public string PlaceBirth { get; set; }
[Display(Name = "Datum testiranja ispitanika:")]
[DataType(DataType.Date)]
public DateTime TestDate { get; set; }
[Display(Name = "Godina rođenja majke:")]
[Range(1900, 2000)]
public int MumDate { get; set; }
[Display(Name = "Godina rođenja oca:")]
[Range(1900, 2000)]
public int DadDate { get; set; }
[Display(Name = "Dropdown_test:")]
public string MumSport { get; set; }
[NotMapped]
public List<SelectListItem> MumSports { set; get; }
}
Controller:
public async Task<IActionResult> Create([Bind("StudentId,StudentNumber,DateBirth,PlaceBirth,TestDate,MumDate,DadDate,MumSports")] student student)
{
if (ModelState.IsValid)
{
var MumSports = new student
{
MumSports = new List<SelectListItem>
{
new SelectListItem { Text = "nikako", Value = "1" },
new SelectListItem { Text = "rekreativno", Value = "2" },
new SelectListItem { Text = "amaterski", Value = "3" },
new SelectListItem { Text = "profesionalno", Value = "4" }
}
};
_context.Add(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(student);
}
View:
<select asp-for="StudentId" asp-items="#(ViewBag.MumSports)">
<option>Please select one</option>
</select>
</div>
Problem is about View, when i run my app, it shows me the dropdown but without data I created in the controller. I think that this is not good way for creating View. Any idea ??
one thing which you need to make sure of when you populate any content on a page with server derived information is that you pass it down correctly.
From your view, i can see that you are looking for a ViewBag.MumSport. So, that means that in the "get" request of your action, you wil need to populate ViewBag.MumSport with the related values.
The controller youve written also looks a bit confusing... we typically expect to have a "get (verb)" controller which you use to set the page up. We usually do things like create the values for the drop down list and populate anything you need for the page. Usually, no saving of data happens here. However, it appears as though you are saving the drop down list to a database?
I believe you might want something like this:
public IActionResult Create()
{
ViewBag.MumSport = new List<SelectListItem>
{
new SelectListItem { Text = "nikako", Value = "1" },
new SelectListItem { Text = "rekreativno", Value = "2" },
new SelectListItem { Text = "amaterski", Value = "3" },
new SelectListItem { Text = "profesionalno", Value = "4" }
}
return View();
}
[HttpPost]
public IActionResult Create(view model goes in here)
{
Business logic goes here
}
This should mean that your drop down list gets populated but it also shows a distinction between the post and get methods. Post is typically where you would create or save inforamtion to a store (database).
Hope this helps
UPDATE
instead of having all the properties as part of the signature for the post method, you can try using the model you have created:
public async Task<IActionResult> Create(student viewModel)
You then need to make sure your input items on the form have names which match up with the viewmodel (student):
<select asp-for="StudentId" asp-items="#(ViewBag.MumSports)">
if you do this, your properties should automatically bind to the viewModel when you hit the controller. Another benefit of doing it this way is that ModelState.IsValid will then look at all the attributes within that class and perform validation against them when you submit the form. This is particularly useful when setting fields as required using the [Required] attribute

asp.net mvc multiple dropdrownlist

I have a form that loads some Partial Views dinamically and one of these Partial Views will load multiple dropdownlists in the screen.
I have a ViewModel (principal): used in the main view
public class CupomFiscalDetalhesViewModel
{
//some properties
public IEnumerable<CupomItensViewModel> CupomItens { get; set; }
}
An intermediate ViewModel: the view model of the partial view:
public class CupomItensViewModel
{
public IEnumerable<TabelaPrecoViewModel> TabelasPreco { get; set; }
public TabelaPrecoViewModel TabelaPrecoSelecionada { get; set; }
}
Where TabelaPrecos is holding the values that I want to show in the DropDownList. and TabelaPrecoSelecionada will hold the selected value.
In the Controller, I'm used to put the values of an IEnumerable into a ViewBag, and use this ViewBag to generate the dropdownlist in the HTML, like this:
ViewBag.TabelaPrecoSelecionada = new SelectList
(
detalhesCupomFiscal.CupomItens.FirstOrDefault().TabelasPreco,
"IdTabela",
"NomeTabela"
);
But I have no idea how to generate multiple dropdowns for each option of CupomItensViewModel, without passing the id of the selected value of each dropdownlist to the controller action (by parameter).
In the Html, I use: but would need to change the name to get binding workin somehow.
#Html.DropDownList("TabelaPrecoSelecionada",(IEnumerable<SelectListItem>)ViewBag.TabelaPrecoSelecionada,
new { #class = "form-control dropdown" })
Does anyone has an Idea how to accomplish it?
I haven't test this but I would maybe create the select list inside your CupomItensViewModel
using System.Linq;
public class CupomItensViewModel
{
public IEnumerable<TabelaPrecoViewModel> TabelasPreco { get; set; }
public TabelaPrecoViewModel TabelaPrecoSelecionada { get; set; }
public IEnumerable<SelectListItem> TabelasPrecoSelectList
{
get
{
return TabelasPreco.Select(x => new SelectListItem()
{
Value = x.IdTabela
Text = x.NomeTabela
Selected = TabelaPrecoSelecionada.IdTabela
}
}
}
}
And Inside your view
#foreach(var item in Model.CupomItens)
{
#Html.DropDownList("TabelaPrecoSelecionada", item.TabelasPrecoSelectList, new { #class = "form-control dropdown" })
}
But if these dropdowns aren't going to be next to each other, I would make
public IEnumerable<CupomItensViewModel> CupomItens { get; set; }
List instead and using index to identify them. CupomItens[x]
Just my 2 cent without checking if it works. Hopefully it helps.

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)

Categories