This is what I'm trying to accomplish.
Basically I have Currency model which contains ID,Name, BuyValue, MidValue, SellValue, and DateCreated.
Now I want to use them in converter I've come up with. It has two drop down lists, where first ddl is From which currency is converted and second To which currency it is converter. Regular stuff.
The first ddl should always contain Name as text in ddl and BuyValue as value, whereas second should always contain Name as text and SellValue as value. Something like this in simple HTML terms.
<select id="ddlFirst">
<option value="BuyValue1">Name1</option>
<option value="BuyValue2">Name2</option>
...
</select>
<select id="ddlSecond">
<option value="SellValue1">Name1</option>
<option value="SellValue2">Name2</option>
...
</select>
Of course this isn't the code for it, it's just clarifying the explanation above.
I'm quite a beginner on this matter, and literally have no clue where to start. What gets me the most is should I somehow separate those values into different models and create a view model out of them or could I just use them somehow. To be honest I'm quite confused so any help is appreciated.
UPDATE
var currencies = db.Currencies.Where(c => c.DateCreated.Equals(today));
var list = currencies.Select(s => new { s.ID, s.Name, s.BuyValue, s.SellValue }).ToList();
var model = new ConverterViewModel
{
FromValues = list.Select( x => new SelectListItem { Value = x.BuyValue.ToString(), Text = x.Name}),
ToValues = list.Select(x => new SelectListItem { Value = x.SellValue.ToString(), Text = x.Name }),
};
This comes up empty though. :( And I know it's not.
What gets me the most is should I somehow separate those values into
different models and create a view model out of them or could I just
use them somehow.
Yes, of course, you should define a view model:
public class MyViewModel
{
public string From { get; set; }
public IEnumerable<SelectListItem> FromValues { get; set; }
public string To { get; set; }
public IEnumerable<SelectListItem> ToValues { get; set; }
}
and then have a controller action populate this view model and pass it to the view:
public ActionResult SomeAction()
{
var currencies = _db.Currencies.ToList();
var model = new MyViewModel
{
FromValues = currencies.Select(x => new SelectListItem { Value = x.BuyValue.ToString(), Text = x.Name }),
ToValues = currencies.Select(x => new SelectListItem { Value = x.SellValue.ToString(), Text = x.Name })
};
return View(model);
}
and finally have a strongly typed view:
#model MyViewModel
<div>
#Html.LabelFor(x => x.From)
#Html.DropDownListFor(x => x.From, Model.FromValues)
</div>
<div>
#Html.LabelFor(x => x.To)
#Html.DropDownListFor(x => x.To, Model.ToValues)
</div>
Related
Can anyone explain why my drop-down list automatically allows multiple selections?
I'm quite new to Net Core and this is the first time I add a drop-down and I'm obvisouly doing something wrong. Everything works technically, the drop-down list is populated and the Model gets the correct data when posting but for some reason the multiple attribute is automatically set for the drop-down list.
View
<select asp-for="#Model.fooForm.CountryRows"
asp-items="#(new SelectList(Model.fooForm.CountryRows,"CountryCode","CountryName"))"
class="form-control">
<option>Please select Country of use</option>
</select>
ViewModel
namespace foo.Models.ViewModels
{
[Bind(Prefix = nameof(fooIndexRootVM.fooForm))]
public class fooVM
{
public fooVM()
{
}
public fooVM(CountryVM[] countryRows)
{
CountryRows = countryRows;
}
[Display(Name = "Country of use")]
public virtual CountryVM[] CountryRows { get; set; }
}
}
Controller/Service
public async Task<fooIndexRootVM> GetCountries()
{
var countryRows = await fooContext.Country
.OrderBy(c => c.CountryCode)
.Select(c => new CountryVM
{
CountryCode = c.CountryCode
,CountryName = c.CountryName
,CountryBlocked = c.CountryBlocked
})
.ToArrayAsync();
return new fooIndexRootVM
{
fooForm = new fooVM(countryRows)
};
}
From MSDN: The select tag helper
The Select Tag Helper will automatically generate the multiple =
"multiple" attribute if the property specified in the asp-for
attribute is an IEnumerable.
So in your case the model it's looking at represents a list for asp-for="#Model.fooForm.CountryRows".
In order to fix this you can add new property for selected country to model
public virtual CountryVM SelectedCountry { get; set; }
Then asp-for should be like this:
<select asp-for="#Model.fooForm.SelectedCountry"
asp-items="#(new SelectList(Model.fooForm.CountryRows,"CountryCode","CountryName"))"
class="form-control">
<option>Please select Country of use</option>
</select>
I'm doing something horribly simple and it isn't working.
#Html.DropDownListFor(m => m.ContentDefinitionID, Model.ContentBoxesSelectList, new {#class = "form-control"})
The ContentDefinitionID is a UInt64 (although I've tried an int)
I use this same select list for 4 different controls on the page.
If my Model.ContentDefinition is set to 4, (which would be test4 in the drop down) then it SHOULD pull that selected value from the Model, NOT from the selectList right? Someone else said that it ignores the value on the SelectList when you use the m=>m.X syntax - which makes sense.
But it always selects the first one. I tried adding another parameter for what it should select, but it wants the text, not the value and I hate to have to lookup the text. (And I'm not sure this will post back correctly if I do that anyway)
I'm about to go create some JQuery code to set the default values for everything -but that is crazy. This is the obvious behavior of the DropDownListFor() method, kind of a 'duh' thing - why doesn't it work? Do I need to create a custom SelectList for every control that exists on the page?
--- Update, the model etc:
class PageModel
{
Int64 ContentDefinitionID {get;set;}
SelectList ContentBoxesSelectList {get;set;}
}
Controller init for model:
model.ContentDefinitionID = 4; // In real situation, this is an
array of N model.ContentBoxesSelectList = new SelectList( from
ContentDefinitionDocument doc in allContentBoxes
where doc.Size == size
select new {Name = doc.Name, id = doc.DefinitionID}, "Id", "Name");
Rendered Output (from it as an array):
selected value should be: 1
<select class="form-control" data-val="true" data-val-number="The field ContentDefinitionID must be a number." data-val-required="The ContentDefinitionID field is required." id="ContentBoxes_0__ContentDefinitionID" name="ContentBoxes[0].ContentDefinitionID" style="width:25%;float:left"><option value="1">Test1</option>
<option value="2">Test 2</option>
<option value="4">Test 4</option>
<option value="0">Test 0</option>
</select>
And None of them are selected.
From the html your generating (name="ContentBoxes[0].ContentDefinitionID"), you are using this in a for loop. Unfortunately DropDownListFor() does not work as expected in a for loop and you need to use a custom EditorTemplate for your model (its been reported as a bug but not yet fixed).
You have not posted your models, but assuming
public class ContentBox
{
public int ContentDefinitionID { get; set; }
....
}
public class ContentBoxesVM
{
public IEnumerable<ContentBox> ContentBoxes { get; set; }
public SelectList ContentBoxesSelectList { get; set; }
}
Side note: Its only necessary to generate one SelectList (rather that one for each object in the collection)
Controller
public ActionResult Edit()
{
ContentBoxesVM model = new ContentBoxesVM();
// populate model, for example
model.ContentBoxes = new List<ContentBox>()
{
new ContentBox { ContentDefinitionID = 4 }
};
model.ContentBoxesSelectList = new SelectList(...);
return View(model);
}
Editor Template (/Views/Shared/EditorTemplates/ContentBox.cshtml)
#model ContentBox
....
#Html.DropDownListFor(m => m.ContentDefinitionID, (SelectList)ViewData["contentBoxesList"])
...
Main view
#model ContentBoxesVM
#using(Html.BeginForm())
{
....
// pass the select list as additional view data to the editor template
#Html.EditorFor(m => m.ContentBoxes, new { contentBoxesList = Model.ContentBoxesSelectList })
....
<input type="submit" />
}
You can achieve what you want by changing your model:
class PageModel
{
Int64 ContentDefinitionID {get;set;}
List<ContentDefinitionDocument> ContentBoxesList {get;set;}
}
and in controller:
array of N model.ContentBoxesList = allContentBoxes.Where(doc => doc.Size == size).ToList();
and in View create SelectList this way:
#Html.DropDownListFor(m => m.ContentDefinitionID,
new SelectList(Model.ContentBoxesSelectList,
"DefinitionID",
"Name",
Model.ContentDefintionID),
new {#class = "form-control"})
I believe this will create a list in my HomeController. But not sure what calls it or where it goes in the Controller beside maybe the first Add ActionResult (GET method).
public static IEnumerable<SelectListItem> items()
{
using (oesacEntities_compact db = new oesacEntities_compact())
{
var query = from s in db.tblSponsors select new { s.SponsorID, s.BizName };
return query.AsEnumerable()
.Select(x => new SelectListItem
{
Value=x.SponsorID.ToString(),
Text = x.BizName
}).ToList();
}
}
I can't seem to send it to the Add view or to reference it from the Add view:
<div class="editor=field">
#Html.DropDownListFor(model => model.SponsorID,IEnumerable<SelectListItem> SelectList);
</div>
It seems so simple in other coding languages. I want to populate a pulldown with about 200 sponsor ID's for value, BizNames for text. For now at least. God help me after that when I want to show an Edit view with the value selected.
thankyou stackoverflow
You need to pass the SelectList to your view. Ideally your view model should include a property for the SelectList but you can (yuk) use ViewBag, for example
View Model
public class MyViewModel
{
public int SponsorID { get; set; }
// other properties
public SelectList SponsorList { get; set; }
}
Controller
public ActionResult SomeThing()
{
MyViewModel model = new MyViewModel();
// assign the select list
var sponsors = from s in db.tblSponsors;
model.SponsorList = new SelecList(sponsors, "SponsorID", "BizName");
return View(model);
}
View
#Html.DropDownListFor(model => model.SponsorID, Model.SponsorList);
or if you assigned the select list to ViewBag
#Html.DropDownListFor(model => model.SponsorID, (SelectList)ViewBag.SponsorList);
New to MVC trying to populate a dropdown from Database, proving a bit more tricky than I imagined.
Here's what I have.
public class EmployeeDetailsModel
{
public string SelectedEmployee { get; set; }
public IEnumerable<SelectListItem> Employees { get; set; }
}
Controller
public ActionResult MiEmployeeDetails()
{
var model = new EmployeeDetailsModel();
model.Employees = _db.geo_employees.ToList().Select(x => new SelectListItem
{
Value = x.name,
Text = x.name
});
return View(model);
}
View
<%= Html.DropDownListFor(x => x.SelectedEmployee, (SelectList) Model.Employees) %>
But getting the error
CS1963: An expression tree may not contain a dynamic operation
You should not cast your IEnumerable to the SelectList - you need to create a new instance of it:
<%= Html.DropDownListFor(x => x.SelectedEmployee, new SelectList(Model.Employees)) %>
Update. While the comment above holds, the actual problem turned out to be dynamically typed view. Such views do not allow use of lambdas in helpers, such as x => x.SelectedEmployee in question. So the actual solution to the problem was making view strogly typed:
Inherits="System.Web.Mvc.ViewPage<Namespace.EmployeeDetailsModel>
Because Employees is an IEnumerable<SelectListItem>, you don't need to cast it or create a new SelectList(), you can just use it directly.
Also I suspect you are missing a .ToList()
public ActionResult MiEmployeeDetails()
{
var model = new EmployeeDetailsModel();
model.Employees = _db.geo_employees.ToList().Select(x => new SelectListItem
{
Value = x.name,
Text = x.name
}).ToList();
return View(model);
}
ToList should be moved to the end of the statement:
model.Employees = _db.geo_employees.Select(x => new SelectListItem
{
Value = x.name,
Text = x.name
}).ToList();
I tried for hours to get it work, but now I have to ask..
As read in
/942262/add-empty-value-to-a-dropdownlist-in-asp-net-mvc and
/3780614/mvc-clear-default-selected-value-of-selectlist
I want to add an empty space to dropdown lists in my ASP.NET MVC Razor WebApp with Entity Framework 5 to force the user for an input.
I followed the informations, but what happend in the View is that: http://i.stack.imgur.com/EXSgT.png
So, as you see, there is an empty space, but it isn't selected by default. Instead, my "testproject", as first value from my controller, is marked.. Not the empty space.
So where did I fail?
Thanks a lot.
My model looks like that:
[...]
using System.Web.Mvc;
public class UploadTranferContainer
{
[DisplayName("Project")]
public int ProjectID { get; set; }
public SelectList Projects { get; set; }
}
My controller fills the data in like:
UploadTranferContainer container = new UploadTranferContainer();
container.Projects = new SelectList(db.Projects.AsEnumerable(), "ProjectID", "ProjectName");
And the view unpacks my container like:
<div class="editor-label metadataLabel">
#Html.LabelFor(x => x.ProjectID)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ProjectID, Model.Projects, string.Empty)
</div>
you can use below approach for dropdown with empty values
#Html.DropDownListFor(x => x.ProjectID, new SelectList(Model.Projects, "ProjectID", "ProjectName"), " ")
The selected value of the dropdown will be the value (if found) of Model.ProjectID
If you want this to appear as the first (empty) option of the select, make sure the value of ProjectID is not contained in the select list items Model.Projects
Allows to create a empty list item
var area = new[] { new tbl_Area { AreaID = -1, AreaName = "Please Select Main Area" } };
or
ViewBag.SubAreaList = new[] { new tbl_Area { AreaID = -1, AreaName = "Please Select Main Area" } };
razor
#Html.DropDownList("DdlSubAreas", new SelectList(ViewBag.SubAreaList, "AreaID", "AreaName"), new { size = "10" });
tbl_Area can be a class or datamodel
class tbl_Area{
public int AreaID {get;set;}
public string AreaName {get;set;}
}