Passing a viewbag to a #Dropdownlist - asp.net-mvc

I'm trying to pass view bag to a DropDownList but is not working.
Dropdownlist Error
view
<div class="form-group">
#Html.LabelFor(model => model.BanhoTosaId, "BanhoTosaId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TransporteId", ViewBag.BanhoTosaId, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BanhoTosaId, "", new { #class = "text-danger" })
</div>
</div>
Controller
// GET: AgendaBTs/Create
public ActionResult Create(int id, int pet)
{
ViewBag.BanhoTosaId = new SelectList(db.BanhoTosas, "BanhoTosaId", "Tipo");
ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome", id);
ViewBag.PetId = new SelectList(db.Pets, "PetId", "PetNome", pet);
ViewBag.TransporteId = new SelectList(db.Transportes, "TransporteId", "Tipo");
if (ViewBag.BanhoTosaId != null && ViewBag.SelectedValue != null)
{
BanhoTosa BT = db.BanhoTosas.Find(ViewBag.BanhoTosaId);
Transporte TS = db.Transportes.Find(ViewBag.TransporteId);
decimal valorSoma = BT.Valor + TS.Valor;
ViewBag.Total = valorSoma;
}
else
{
ViewBag.Total = 0;
}
return View();
}
If I let the dropdown this way #Html.DropDownList("TransporteId",null, htm....
the if in the controller you throw the else method.
How can i do to solve this?

you first need to make a list from data you wanna fill list by it like that :
List<Category> CatList = db.Categories.ToList();
and then use a ViewBag :
ViewBag.CategoriesList = new SelectList(CatList, "CategoryID", "CategoryName");
after that you will going to view and write:
<div class="form-group" style="margin-left:85px">
<div class="col-md-10">
#Html.DropDownListFor(model => model.CategoryID, ViewBag.CategoriesList as SelectList,
"Select Category", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoryID, "", new { #class = "text-danger" })
</div>
</div>
this example from project i worked on it before

You need to cast the ViewBag.BanhoTosaId:
#Html.DropDownList("TransporteId", (List<SelectList>) ViewBag.BanhoTosaId, htmlAttributes: new { #class = "form-control" })
OR
In your Create action replace this:
ViewBag.TransporteId = new SelectList(db.Transportes, "TransporteId", "Tipo");
By
ViewBag.TransporteId = db.Transportes;
Add then in your razor view:
#Html.DropDownList("TransporteId", new SelectList(ViewBag.TransporteId , "TransporteId", "Tipo"))

Replace
#Html.DropDownList("TransporteId", ViewBag.BanhoTosaId, htmlAttributes: new { #class = "form-control" })
with
#Html.DropDownList("TransporteId", (IEnumerable<SelectListItem>)ViewBag.BanhoTosaId,null, new { #class = "form-control" })

Related

How to disable a textbox while when we hit edit option in edit.cshtml page in mvc?

====> Here is my edit.cshtml page code:
<div class="form-group">
#Html.LabelFor(model => model.Eno, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Eno, new { htmlAttributes = new { #class = "form-control" } } )
#Html.ValidationMessageFor(model => model.Eno, "", new { #class = "text-danger" })
</div>
</div>
I want to disable this textbox. Can anyone help me with that.
This is my Controller:
[HttpGet]
public ActionResult Edit(int id)
{
Models.Employee e1 = new Models.Employee();
e1.Eno = id;
e1 = objdalemp.SearchEmp(e1);
return View(e1);
}
[HttpPost]
public ActionResult Edit(Models.Employee e1)
{
int i = objdalemp.UpdateEmployee(e1);
if(i==1)
{
return RedirectToAction("Index");
}
return View(e1);
}
You can disable a html field generated using the following
#Html.EditorFor(model => model.Eno, new { htmlAttributes = new { #class = "form-control", #disabled = "disabled" } }).
You can disable like below.
#Html.EditorFor(model => model.Eno, new { htmlAttributes = new { #disabled ="true", #class = "form-control" } })

DropDownListFor - need help defining "SelectedValue" property

I need help understanding how to set the SelectedValue property in HTML.DropDownListFor.
Here's what I have so far:
In another part of the model, MA is an int that is stored on the database.
In the Model:
public IList<SelectListItem> SelectListMA(int MA)
{
IList < SelectListItem > List = new List<SelectListItem>();
SelectListItem Item;
for(int i = 1; i <= 9; i++)
{
Item = new SelectListItem
{
Value = i.ToString(),
Text = i.ToString(),
Selected = i == MA
};
List.Add(Item);
}
return List;
}
In the controller:
ViewBag.MA = _Repository.SelectListMA(5);
And finally, in the View:
#Html.DropDownListFor(model => model.MA, new SelectList(ViewBag.MA, dataValueField: "Value", dataTextField: "Text"))
In the View the dropdown displays fine, however the default value is not being set and I am using the model to pass the original model for editing to View hence using ViewBag
Edit: Further details Requested - this is the full Controller that this belongs to.
private readonly IRacesRepos _RaceRepository;
public BaseTeamsController(IRacesRepos _Repository)
{
_RaceRepository = _Repository;
}
//sets the Model to the repository
public BaseTeamsController() : this(new ModelRaces()) { }
public ActionResult BEditPlayer(int ID)
{
Races_Players SelectedPlayer = _RaceRepository.GetPlayerBase(ID);
ViewBag.MA = _RaceRepository.SelectListMA(SelectedPlayer.MA);
ViewBag.ST = _RaceRepository.SelectListST(SelectedPlayer.ST);
ViewBag.AG = _RaceRepository.SelectListAG(SelectedPlayer.AG);
ViewBag.PA = _RaceRepository.SelectListPA((int)SelectedPlayer.PA);
ViewBag.AV = _RaceRepository.SelectListAV(SelectedPlayer.AV);
ViewBag.Race = _RaceRepository.GetRaceBase(SelectedPlayer.RaceID);
return View(SelectedPlayer);
}
And I am using MVC version 5, and ModelRaces is the name of the model that contains the code, MA is an int in the model from the database.
Full View
#model BB2020MVC.Models.Races_Players
#{
ViewBag.Title = "Add Player to " + ViewBag.RaceName;
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Add Player to #ViewBag.RaceName</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PlayerID)
#Html.HiddenFor(model => model.RaceID)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10 focus">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MA, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.MA, new SelectList(ViewBag.MA, dataTextField: "Text", dataValueField:"Value") , new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MA, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ST, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ST, new SelectList(ViewBag.ST, dataTextField: "Text", dataValueField: "Value"), new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ST, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AG, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.AG, new SelectList(ViewBag.AG, dataTextField: "Text", dataValueField: "Value"), new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AG, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PA, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.PA, new SelectList(ViewBag.PA, dataTextField: "Text", dataValueField: "Value") ,new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PA, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AV, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.AV, new SelectList(ViewBag.AV, dataTextField: "Text", dataValueField: "Value") ,new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AV, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Cost, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Cost, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Cost, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MaxQTY, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MaxQTY, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MaxQTY, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Cancel", "ViewRace", new { ID = Model.RaceID })
</div>
Edit: Been doing a bit of testing and reading, issue seems to be that the view is not selecting the selected value of model => model.MA yet the value is not null on editing so any value that has been selected by SelectListItem or SelectList is ignored.
Also passing any value into selectedValue other than a number or word (eg "1" or "Word", not a variable of type int or string) causes the item to not be selected.
Doesn't fix the issue but an interesting point.
Try this syntax:
in the view
#Html.DropDownListFor(model => model.MA, ViewBag.MA,"Select One", new { htmlAttributes = new { #class = "form-control" } })
in repository:
public SelectList SelectListMA(int MA)
{
var List = new List<SelectListItem>();
for(int i = 1; i <= 9; i++)
{
List.Add(new SelectListItem
{
Value = i.ToString(),
Text = i.ToString(),
});
}
return new SelectList(list, "Value", "Text",MA);
}
But you don't need to convert to List of SelectListItem your existed lists.
Just use retun new SelectList(yourlist, "yourvalueproperty", "yourtextproperty",);
The answer to this one lies between the keyboard and the screen.
Let me explain:
In the additional testing I had erroneously changed _RaceRepository.GetPlayerBase(ID) to another function that generates a new base for the record. (an impromptu Mutation Test!)
This meant every time I was trying to edit the player, I was passing the default value of "1 to the view and upon submission edited a model that never existed in the first place.
Upon setting the correct function, I was getting the correct values and thus the setting of the selected value sorted itself out.
I will however thank Sergey for having a look and trying to assist, and providing a better way of providing a SelectList (A better version would be to use a ViewModel, that will have to be used for another part).
So for those that are interested, here is the code that solves this issue:
From the Model:
public SelectList SelectListMA()
{
IList<SelectListItem> List = new List<SelectListItem>();
SelectListItem Item;
for(int i = 1; i <=9; i++)
{
Item = new SelectListItem()
{
Value = i.ToString(),
Text = i.ToString()
};
List.Add(Item);
}
return new SelectList(List,"Value","Text");
}
From the Controller:
public ActionResult BEditPlayer(int ID)
{
Races_Players SelectedPlayer = _RaceRepository.GetPlayerBase(ID);
ViewBag.MASelect = _RaceRepository.SelectListMA();
ViewBag.STSelect = _RaceRepository.SelectListST();
ViewBag.AGSelect = _RaceRepository.SelectListAG();
ViewBag.PASelect = _RaceRepository.SelectListPA();
ViewBag.AVSelect = _RaceRepository.SelectListAV();
return View(SelectedPlayer);
}
From the View: - as SelectList is to stop errors happening as the code is built
#Html.DropDownListFor(model => model.MA, ViewBag.MASelect as SelectList, "Select One")
Also, for any new programmers as per the research and testing, SelectList and SelectListItem have SelectedValue and Selected respectively for selecting Default values.
SelectedValue can be any object that identifies the primary key of the list or a new default value of the list (eg integer for a value already in the list, or a string for a default value of null).
Selected, however, is a boolean (ie true or false) that selects the value of the list. You only need to use one or the other.
Remember - if the value is passed from the controller to the view as the value in model => model.[Variable] then the value will be set to the value passed, not to the value set by SelectedValue or Selected.

MVC, Edit View problem with getting existing data in form

I got a problem when I create edit view. I run program, from index view and click on edit on some data.
Issuse is that Im getting empty form(I can save it to database normaly) but I want to see what I entered and than edit some parts of data and save it.
public ActionResult Edit(int Id)
{
IEnumerable<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact item = db.Contacts.First(x => x.ContactId == csvm.ContactId);
item.CountryId = csvm.CountryId;
item.StateId = csvm.StateId;
item.ImeOsobe = csvm.ImeOsobe;
item.PrezimeOsobe = csvm.PrezimeOsobe;
item.Komentar = csvm.Komentar;
item.Email = csvm.Email;
item.Aktivan = csvm.Aktivan;
item.kcbr = csvm.kcbr;
item.KucniBroj = csvm.KucniBroj;
item.NazivUlice = csvm.NazivUlice;
item.NazivNaselja = csvm.NazivNaselja;
item.PostanskiBroj = csvm.PostanskiBroj;
item.KontaktBroj = csvm.KontaktBroj;
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
}
public class EditStateContactViewModel : CountryStateContactViewModel
{
public int Id { get; set; }
}
And View
#model AkvizicijeApp_4_2.Models.EditStateContactViewModel
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
<h2>Edit</h2>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger" })
</div>
</div>
.....
and scripts from View for Parent-Child dropdown lists
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
});
});
})
});
</script>
You didn't select existing data to edit form.
You need to load your DB data to viewmodel and pass your viewmodel to cshtml by return View(vm):
[HttpGet]
public ActionResult Edit(int Id)
{
IEnumerable<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
var item = db.Contacts.First(x => x.ContactId == Id);
var vm = new EditStateContactViewModel();
vm.Id = Id;
vm.NazivNaselja = item.NazivNaselja;
...
return View(vm);
}

HiddenInput not working while render on view MVC 5

I have used HiddenInput(DisplayValue = false) like:
[HiddenInput(DisplayValue = false)]
[DisplayName("Updated By")]
public string Updatedby { get; set; }
but it's still rendering as EditorFor
<div class="form-group">
#Html.LabelFor(model => model.Updatedby, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Updatedby, new { htmlAttributes = new { #class = "form-control" } }) #Html.ValidationMessageFor(model => model.Updatedby, "", new { #class = "text-danger" })
</div>
</div>
I want to render it as hidden field. How can I do that? Thank you.
You can use
#Html.HiddenFor(m=>m.Updatedbynew ,new { #class = "form-control" })
for rendering a hidden model-binded field in DOM.

How to save dropdown values in database in asp.net MVC

When I select category from dropdown it is not saving in database. In database it is showing 101 for all values
MY view.cshtml is
<h4>RecStock</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="editor-field">
#Html.DropDownList("Category",null, new { #class = "form-control" } )
</div>
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
My Controller is
public ActionResult Create()
{
ViewBag.Category = new SelectList(db.ProductDetails, "id", "Category");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Category,ProductName,ReceiveQty,Date")] RecStock recStock)
{
if (ModelState.IsValid)
{
db.RecStocks.Add(recStock);
ViewBag.Category = new SelectList(db.ProductDetails, "id", "Category", recStock.id);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(recStock);
}
You should be using "DropDownListFor" and assign the selected dropdown value to the corresponding model property, like this:
#Html.DropDownListFor(m => m.MyModelProperty, new SelectList(Model.ListOfStuff, "ListOfStuffId", "ListOfStuffName"), string.Empty, new {#class = "form-control", id = "myList"})

Resources