I am trying to develop a web application which I Need to save firm name username and password.
When I try to add firm username and password it gives me same firm ID in the database as;
Firmname : YAHOO INC
UserName : asd
Password : pass
İn formload all firms come but when ı try to save firmname, username and pass it gives me same firmname for all user save.
Any advice how I can resolve such issue?
Here is a simple example of how to create a drop down list in ASP.NET MVC using Html.DropDownListFor.
You can do it like this all inlined in your *.cshtml file like so:
#Html.DropDownListFor(model => model.Package.State, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"}
},
"value",
"text",
2))
With produces this:
<select id="Package_State" name="Package.State"><option value="0">Red</option>
<option value="1">Blue</option>
<option value="2">Green</option>
</select>
The model => model.Package.State expression is used to generate the id and name on the select.
The string value and text matter as they need to match the model attributes of the listItem in the list.
Or you can create your own List collection (with different fields for value and text) in your controller, set it on you model, and then use in your view like this:
#Html.DropDownListFor(model => model.Package.State.Id, new SelectList(
Model.PackageStates,
"id",
"name",
Model.Package.State.Id))
Related
I am doing the CRUD for the table called Recipe. The whole functionality is already created in an API and at this point, I am trying to implement it on a web page. During the creation of a new recipe, you have to complete some fields such as TotalTimeUnitId. This is a column in the Recipe table that only takes integers; however, in the user interface you have to pick from a list with seconds/minutes/hours, their value being the thing that needs to be passed in the database through the controller.
<div class="form-group">
#Html.LabelFor(model => model.TotalTimeUnitId)
#Html.EditorFor(model => model.TotalTimeUnitId)
#Html.ValidationMessageFor(model => model.TotalTimeUnitId)
<select id="list" onchange="getSelectedtValue();">
<option value="1">seconds</option>
<option value="2">minutes</option>
<option value="3">hours</option>
</select>
<script>
function getSelectedtValue() {
var selectedValue = document.getElementById("list").value;
console.log(selectedValue);
}
getSelectedtValue();
</script>
This is the code that I wrote trying to achieve this. If you pick, let's say, minutes from the list, the getSelectedValue() function returns "2". How can I be able to call this method inside the EditorFor so the variable TotalTimeUnitId will be assigned the value? Is there another way to doing this?
#Html.DropDownListFor(
model => model.TotalTimeUnitId,
new SelectList(
new List<Object>{
new { value = 1 , text = "Seconds" },
new { value = 2 , text = "Minutes" },
new { value = 3 , text = "Hours"}
},
"value",
"text",
Model.TotalTimeUnitId
)
)
This did the job.
Been googling for a while, but I can't seem to get any closer.
I'm using MVC with an EF Database structure.
I want the dropdownlist items in the View to show up with different names than what they come up with.
Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name. Eventually, the selected field needs to be used in another lambda as the Byte that it was.
Edit
//view
<p>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
#Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })
....
//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
orderby t.TYPE
select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);
....
Thanks in advance.
You can create a SelectListItem to display in your dropdownlist.
Example:
#Html.DropDownListFor(model => model.YearStartedToPay,
Enumerable.Range(DateTime.Today.Year - 60, 61).OrderByDescending(x => int.Parse(x.ToString())).Select(n => new SelectListItem() { Text = n.ToString(), Value = n.ToString(), Selected = false }).ToList<SelectListItem>(),....)
In this case, I'm creating an Enumerable, that will be your list returned from EF, ordering and selecting as a SelectListItem.
You need to make use of dropdownlist's Value property. Make your list a type of SelectListItem.
Assign Text= [Your Required Text] and Value = [Current Name]
I'm building an MVC web application and am about to run my head through the wall, there's a dozen topics on this already and all have accepted solutions that do not work for me. There's probably something really stupid and simple I'm forgetting/not seeing, but can't seem to work it out.
Please don't hate me for naming; I'm continuing a project started by someone else.
I have the following line in my ManageDetail.cshtml:
#Html.DropDownListFor(m => m.ChecklistWaarde.SoortID, Model.ChecklistOptionsOptions, "Choose a value", new { #class = "form-control" })
This builds a selectbox based on property Model.ChecklistWaarde.SoortID, which is an integer. The next parameter passed is a SelectList from the model that is generated by the following very simple helper function that does a DB lookup in a 2ndary database (unfortunately), it receives the parameter SoortID as well to set a preselect value:
public SelectList GetChecklistOptions(int selectedId = -1)
{
var soorten = new List<SelectListItem>();
try
{
using (var connection = new SqlConnection(mssqlConnectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "Select Naam, ID From ChecklistSoorten";
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var id = reader["ID"] as int?;
if (id.HasValue)
{
soorten.Add(new SelectListItem { Text = reader["Naam"] as string, Value = id.Value.ToString(), Selected = id.Value.Equals(selectedId) });
}
}
}
}
catch (Exception ex)
{
Globals.Log.Error(ex);
}
return new SelectList(soorten, "Value", "Text");
}
It gets called in the controller like this:
public ActionResult ManageDetail(int? id) {
var model = new MachineDetailsModel(id);
model.ChecklistOptionsOptions = sqlDal.GetChecklistOptions(model.ChecklistWaarde.SoortID);
return View("ManageDetail", model);
}
When I try to debug my code, I can see that the model values are populated correctly:
SoortID has a value of 2 (int)
Model.ChecklistOptionsOptions has a populatedSelectList
Upon inspecting the SelectList I find that only item with value "2" has property Selected = true, this is false for all others.
When the form gets rendered, it will not select the item with value 2, rather it will have the first item selected, "Choose a value"
Inspecting the HTML, I see that the item with value 2 is indeed not selected, contrary to what I was expecting (see HTML below; shorted the list in count and text for readability). I expected to see "selected" on the line for item 2, as it was selected in the SelectList.
<select class="form-control" data-val="true" data-val-number="The field SoortID must be a number." data-val-required="The SoortID field is required." id="ChecklistWaarde_SoortID" name="ChecklistWaarde.SoortID" style="min-width:100%;">
<option value="">Choose a value</option>
<option value="1">Item A</option>
<option value="2">Item B</option>
<option value="3">Item C</option>
<option value="4">Item D</option>
</select>
What am I missing? How can I make item with value "2" select, as it is in the SelectList that I pass to the DropDownListFor() function?
In the controller where you are populating SelectList, set selected value there, your code would look like:
if (id.HasValue)
{
soorten.Add(new SelectListItem
{
Text = reader["Naam"] as string,
Value = id.Value.ToString()
});
}
and then down at the line of instantiating SelectList:
return new SelectList(soorten, "Value", "Text",selectedId);
or you could elminate SelectList and instead in your model change the property ChecklistOptionsOptions type to List<SelectListItem>, in that case the last line of creating SelectList will not be required further, right now you are creating it multiple times.
Ultimately everything in the view that gets rendered comes from ViewData. This takes the model, but also request data and 'ModelState`.
I have had this sort of problem when some of the request parameters have a name conflict with some of the model parameters. This overrides the value in the model and causes the issue.
It is very difficult to debug, as it normally appears that all the correct values have been set. Check all your parameter names if in doubt.
I'm trying to develop a website using asp.net mvc 4 & EF6 where I'm using dropdownlist to assign datas to my required textboxes. So far I've managed to assign data to two textboxes where one holds the value of the selected item of dropdownlist & one holds the text given for the selected item. But I need to add another value from the selected item. My codes are below,
Controller
ViewBag.Clients = new SelectList(db.ClientInfoes, "age", "fullname"); //This is given
ViewBag.Clients = new SelectList(db.ClientInfoes, "id", "age", "fullname"); //I want something like this
View
#Html.DropDownList("Clients", "Select...")
// Textboxes are populated automatically by using jQuery
#Html.TextBoxFor(a => a.Fullname, new { id = "clientName", #readonly = "readonly" })
#Html.TextBoxFor(a => a.Age, new { id = "clientAge", #readonly = "readonly" })
How can I assign more than one value in the SelectList? Any way I can do that would be fine. Need this help badly. Thanks.
It looks like you want to show name and age both in the dropdown text, in that case you need to project the result coming from database :
var ClientInfoes = db.ClientInfoes
.Select(x=>
new {
id = x.id,
name = x.fullname+","+x.age
});
ViewBag.Clients = new SelectList(ClientInfoes, "id", "name");
I am pretty new to MVC. In my form i have a disabled dropdown control whose value is not getting passed to the Model during submit as it is disabled. I tried using a hidden field like below
#Html.DropDownListFor(model => model.DepartmentID, new List<SelectListItem> { new SelectListItem { Text = "Item 1", Value = "1" }, new SelectListItem { Text = "Item 2", Value = "2", Selected = true } })
#Html.HiddenFor(model => model.DepartmentID)
Both of the above statement produce controls having the same id so i was not sure can i get the value of the dropdown in the hidden field.
I could use a different id while creating the hidden variable and assign the dropdown value it it using jquery.
I just want to know if i can achieve the same using the Hidden field having the same id as shown in the above code ??
Form Fields are not submitted by ID, they're submitted by name. It's ok for there to be two controls with the same name. However, it's invalid HTML to have two elements with the same id.
You can set a different ID but keep the same name like this:
#Html.HiddenFor(x => x.DepartmentID, new { id="DepartmentID2" })