I don't know how to sum up what I'm trying to do in the title properly! Basically I have created a controller with EF6 and one foreign key of the Client table is MJTopicsID which links to the MJTopics table, a table of 26 topics. In the add and edit view I want the MJTopicsID to be a drop down menu displaying all the topics available however when you select it and click to add or edit an entry it adds it to the Client table as the MJTopicsID foreign key number? How do I go about this so I can apply it to all of my views.
This is the dropdown menu I created in the edit view however it just shows numbers 1-26 and if I change it to the topics variable it doesn't know it as obviously its not in the open model, thanks!
<div class="form-group">
#Html.LabelFor(model => model.MJTopicsID, "MJTopicsID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("MJTopicsID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MJTopicsID, "", new { #class = "text-danger" })
</div>
</div>
If I understood correctly then you want to display some readable value and save some db specific value like foreign key Id in this case.
In the view for helper method "DropDownList" you can give second parameter of type IEnumerable type as a list of your options like this:
View:
#Html.DropDownList("MJTopicsID",
(List<SelectListItem>)#ViewBag.MJTopics,
htmlAttributes: new { #class = "form-control" })
Action:
public ActionResult Index()
{
ViewBag.MJTopics = new List<SelectListItem>() {
new SelectListItem(){Text = "Topic1", Value ="1" },
new SelectListItem(){Text = "Topic2", Value ="2" }
};
return View();
}
SelectListItem has two properties which you can map with your models.
Also you can use your model with "Text" as value to display and "value" as value to use.
Let "topics" is your list model for topics
then you can write it as
topics.Select(
x=> new SelectListItem()
{
Text = x.Id,
value =x.Desc
})
This is the one way of doing it.
I hope it will solve your problem.
I wanted to add an answer if anyone is new to EF6 and is trying to do the same thing.
In the controller for the actionresult you are trying to do this for, so in my case create it will create a viewbag variable this was mine:
ViewBag.MJTopicsID = new SelectList(db.MJTopicss, "ID", "ID");
I changed it to:
ViewBag.MJTopicsID = new SelectList(db.MJTopicss, "ID", "topicalTF");
The topicalTF is the variable for the topics available and this showed all the topics but would save it as the ID, hope this helps!
Related
I am trying to add a drop down select element to my .net page, but I need it to be black so I can populat it with a json list I have with jQuery. Right now, my view has this:
#Html.DropDownList("Language", new SelectList(" "), "name = 'Laguange'", new { #class = "Language-List field form-group form-control" })
This 'works', but it seems to be confusing some stuff when I try to submit the form it is in. The value I select from it is never seen by the model, as it keeps triggering my [Required] validation helper.
Does anyone know How to add this without the new SelectList(" ") attribute?
I would suggest it's because youre using the name attribute in the wrong place.
Try this:
#Html.DropDownList("Language", new SelectList(" "), new {Name="Language", #class = "Language-List field form-group form-control" })
Notice the capital Name
Although as they are the same, you can just leave it out:
#Html.DropDownList("Language", new SelectList(" "), new {#class = "Language-List field form-group form-control" })
I have an html dropdownlistfor which is being populated from my database, this I was able to do successfully but the issue I am having now is including an additional option not available in the database as an option that can also be selected.it is actually a list of items but I want a give an option ALL which when selected means the user is selecting all the items displayed in the database, my major issue is how to include the ALL option. I have searched and read similar questions but they are not what am trying to achieve. thanks for your help. here is my code
in my controller I have this:
var load = from bh in db.IV_001_ITEM
select bh;
ViewBag.selection = new SelectList(load.ToList(), "item_code", "item_name", glay.vwstring2);
in my view I have this:
<div class="col-sm-2">
#Html.DropDownListFor(m => m.vwstring2, ViewBag.selection as SelectList, "Select", new { #class = "form-control", required = "required", id = "selectc" } )
</div>
You can use the Add method to explicitly add an extra option (SelectListItem)
List<SelectListItem> optionList = db.IV_001_ITEM
.Select(x=>new SelectListItem { Value=x.item.code,
Text=x.itemName}).ToList();
// Now add the item you want
optionList.Add(new SelectListItem { Value="Foo",Text="Bar"});
//use this now
ViewBag.Items = optionList;
// You can set the selected item on your view model property
myViewModelObject.vwstring2 = glay.vwstring2; //For the selected item
return View(myViewModelObject);
In your view,
#Html.DropDownListFor(m => m.vwstring2, ViewBag.Items as List<SelectListItem>,
"Select", new { #class = "form-control"})
I am using below code to create a drop down
Controller
ViewBag.Id= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")
View
#Html.DropDownList("Id", null, htmlAttributes: new { #class = "form-control" })
My question is how can I Modify SelectList to add a blank item so that there is a blank item automatically added for DropDownList.
Thanks.
Use one of the overloads that accepts an optionLabel
#Html.DropDownListFor(m => m.ID, (SelectList)ViewBag.MyList, "Please select", new { #class = "form-control" })
or if you do not want to use the strongly typed methods
#Html.DropDownList("ID", (SelectList)ViewBag.MyList, "Please select", new { #class = "form-control" })
Which will add the first option with the text specified in the 3rd parameter and with a null value
<option value="">Please Select</option>
You can use this overload:
public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes);
where optionLabel is the text for a default empty item.
In my project, these work:
Controller
ViewBag.TagHfoFlagId= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")
View
#Html.DropDownList("TagHfoFlagId", null,"--Select Name--", htmlAttributes: new { #id = "tags" })
The accepted answer does work, but it will show the default (null) value in the view's drop down list even if you already selected one before. If you want the already selected value to show itself in the drop down list once you render back the view, use this instead :
Controller
ViewBag.Fk_Id_Parent_Table = new SelectList(db.Parent_Table, "Id", "Name", Child_Table.Fk_Id_Parent_Table);
return View(ChildTable);
View
#Html.DropDownList(
"Fk_Id_Parent_Table",
null,
"Not Assigned",
htmlAttributes: new { #class = "form-control" }
)
I need to save a selected Item in my Database during User Registration. but it seems as if my selected Item is not recognised. here is the error that it's givin me
"There is no ViewData item of type 'IEnumerable' that
has the key 'Faculties"
Am still unskilled in MVC/C# Programming please help here is my code below; thanks in advance!
My DataModel
public string Faculty { get; set; }
My Controller
public ActionResult Register()
{
DataClasses1DataContext db = new DataClasses1DataContext();
ViewBag.Faculties = new SelectList(db.Faculties, "Id", "Name");
return View();
}
My View
<div class="form-group">
#Html.LabelFor(model => model.Faculty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Faculties","Select Faculty")
#Html.ValidationMessageFor(model => model.Faculty, "", new { #class = "text-danger" })
</div>
</div>
The way you are displaying items in the dropdown is not correct. You can use below code to display the items fetched from your db:
#Html.DropDownList("Faculties", ViewBag.Faculties as IEnumerable<SelectListItem>,
"Select Faculty");
Please note that your ViewBag.Faculties should be casted to Enumerable<SelectListItem>.
To get the selected value of dropdown in controller you can use below method:
var value = Request["Faculties"];
Once you got the value, you can save it in database.
Update:
A good approach will be to bind your View to a model which I think you have already done since I can see you are using model.Faculty. So the dropdown should look something like below in View:
#Html.DropDownList(model => model.Faculty,ViewBag.Faculties as IEnumerable<SelectListItem>,
"Select Faculty");
And your controller where data is posted should be something like below:
[HttpPost]
public ActionResult Register(YourModel model)
{
var selectedFaculty = model.Faculty; //Selected Value
//Save it in database
}
Try changing this line:
ViewBag.Faculties = new SelectList(db.Faculties, "Id", "Name");
to the following
ViewData["Faculties"] = new SelectList(db.Faculties, "Id", "Name");
ViewBag and ViewData are two separate constructs, and cannot be used interchangeably.
It's just the names of your property and your ViewBag are different. change your ViewBag name to match the property name.
ViewBag.Faculty = new SelectList(db.Faculties, "Id", "Name");
Your HTML would be:
#Html.DropDownList("Faculty ","Select Faculty")
Alternatively and (preferably) use a model binding instead of ViewBag
Model
public string Faculty { get; set; }
public IList<SelectListItem> Faculties {get;set;}
Controller
Model.Faculties = new SelectList(db.Faculties, "Id", "Name");
return View(Model);
HTML (View)
#Html.DropDownListFor(m => m.Faculty , Model.Faculties )
On the edit page of my website I want users to be able to edit qty's and then have it change the model. This is why I am using 'editorFor'. The problem is that I still want to return the value of the model before it was edited to the controller post method.
For example, if a user edited a qty from 7 to 10, I would want the model to change to 10 but I would also want the view to return 7 to the controller. How can I do this?
Here is my editorFor code
<div class="form-group">
#Html.LabelFor(model => model.item_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item_qty, "", new { #class = "text-danger" })
</div>
</div>
Here is my edit post method
[RestrictAccess(restriction = AccessRestrictions.ModifyWorkOrder)]
[HttpPost]
[ValidateAntiForgeryToken]
[Audit]
public ActionResult Edit([Bind(Include = "ID,JobOrderID,StartDate,CompleteDate,jobSection,ItemID,item_qty,actual_item_qty,ComponentID,comp_qty,actual_comp_qty,PartID,part_qty,actual_part_qty,Notes,subDetail")] JODetails jODetails)
{
if (ModelState.IsValid)
{
JobOrder jo = db.JobOrders.Find(jODetails.JobOrderID);
db.Entry(jODetails).State = EntityState.Modified;
JODetails currentData = db.JODetails.Find(jODetails.ID);
Component comp = db.Components.Find(jODetails.ComponentID);
Item i = db.Items.Find(jODetails.ItemID);
int newItemCount = jODetails.item_qty != null ? (int)jODetails.item_qty : 0;
int oldItemCount = 0;
int itemDiff = newItemCount - oldItemCount;
}
If I understand well enough, you don't need to return the value from the view. When the model is passed to the controller the value in the database has not been changed, you can read it again. Something like this:
// First. Grab the previous quantity...
// This approach won't work because of EF is already TRACKING the entity
// JODetails currentData = db.JODetails.Find(jODetails.ID);
// So, you have to access data like this...
var currentData = db.JODetails.AsNoTracking().FirstOrDefault(j => j.ID == jODetails.ID);
int previousQuantity = currentData?.item_qty;
//... do whatever with previousQuantity prop & new JODetails model. Don't forget to check if currentData is null
// Just NOW. Mutate the object via EF...
db.Entry(jODetails).State = EntityState.Modified;
// THEN. Commit changes...
db.SaveChanges();
It's not until you SaveChanges() that the record in the database it's really changed. Read some docs about how EF tracks, modifies & save objects.
This could be very helpful to understand this...
https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/examining-the-edit-methods-and-edit-view
Of course if you NEED to retrieve the Quantity data from the view (can't see why) there are some alternatives such as a ViewModel but I think this would do the trick. Yes, with this approach there's one more trip to the database, but it's minimal.