I have a drop down list in my view I want to get the value user selects in my controller action method.
View
Specialty Name Active:
<td>
<select name="Specialty" id="Specialty">
<option>--Select--</option>
<option value="1">True</option>
<option value="0">False</option>
</select>
</td>
Model:
public class GazelleInfoModel
{
public GazelleInfo gazelleInfo { get; set; }
public IList<WCG.Data.EntityObjects.GazelleInfo> ReportModel { get; set; }
}
Controller:
public ActionResult CreateNewGazelleInfo(GazelleInfoModel gazelleinfoModel, string hdnId, )
{
if (!isActive)
return LogOut();
ViewData["CurrentPage"] = "Create New GazelleInfo";
GazelleInfo gaz = null;
if (gaz == null)
{
gaz = new GazelleInfo();
}
gaz.SpecialtyName = gazelleinfoModel.gazelleInfo.SpecialtyName;
gaz.SpecialtyNameActive=
gaz.PreferredLanguage = gazelleinfoModel.gazelleInfo.PreferredLanguage;
gaz.PreferredLanguageActive = gazelleinfoModel.gazelleInfo.PreferredLanguageActive;
gaz.Race = gazelleinfoModel.gazelleInfo.Race;
gaz.RaceActive = gazelleinfoModel.gazelleInfo.RaceActive;
gaz.Ethnicity = gazelleinfoModel.gazelleInfo.Ethnicity;
gaz.EthnicityActive = gazelleinfoModel.gazelleInfo.EthnicityActive;
gaz.HolidayName = gazelleinfoModel.gazelleInfo.HolidayName;
gaz.HolidayNameActive = gazelleinfoModel.gazelleInfo.HolidayNameActive;
GazelleInfoBo.SaveOrUpdate(gaz);
What I need is storing the values selected in the drop downlist in the gaz object which at a later point of time i will store in the database.
Option 1
var Specialty = Request.Form["Specialty"];// here request.form is used to get Specialty form variable.
Option 2 : I would suggest you to use MVC ModelBinding and Html Helpers.
Model - Add new property Specialty
Controller - get all relevant Specialities
ViewBag.Specialities= new SelectList(Specialities, "Value", "Text");
View - User strongly type html helper
#Html.DropDownListFor(x => x.Specialty , new SelectList(ViewBag.Specialities, "Value", "Text", Model.Specialty ))
Option 3 - Best practice to have radiobuttons(where possible) to implement true/false logic.
#Html.RadioButtonFor(x=>x.Specialty, true)True
#Html.RadioButtonFor(x=>x.Specialty, false)False
Related
At the moment I'm trying to insert a value from two dropdown lists. The users aren't allowed to select both dropdown lists at the same time. One at a time.
I have tried different options now, so now I will show you what I have.
The user can select a value from two dropdown lists, when they have selected the radio button they want.
View
In this view, the user can select a value from one of the two dropdown lists.
<div id="Man">
#Html.DropDownList("SeriesID_Man", null, "Vælg serie / årgang", new { #class = "form-control", id = "ddlMan", string.Empty })
</div>
<div id="Women" style="display:none;">
#Html.DropDownList("SeriesID_Women", null, "Vælg serie / årgang", new { #class = "form-control", id = "ddlWomen", string.Empty })
</div>
Controller
In the HttpPost ActionResult method I try to save the selected values
[Route("opret-spiller")]
public ActionResult CreatePlayer()
{
ViewBag.ClubListID = new SelectList(db.ClubLists, "ClubListID", "ClubName");
ViewBag.PositionID = new SelectList(db.Positions, "PositionID", "PositionName", "PositionCategory", 0);
ViewBag.SeriesID_Man = new SelectList(db.Seriess.Where(x => x.GenderID == 0), "SeriesID", "SeriesName", "SeriesCategory", 0);
ViewBag.SeriesID_Women = new SelectList(db.Seriess.Where(x => x.GenderID == 1), "SeriesID", "SeriesName", "SeriesCategory", 0);
return View();
}
[Route("opret-spiller")]
[ValidateInput(false)]
[HttpPost]
public ActionResult CreatePlayer(PlayerProfileViewModel viewModel, Player player)
{
ViewBag.ClubListID = new SelectList(db.ClubLists, "ClubListID", "ClubName", player.ClubListID).SelectedValue;
ViewBag.PositionID = new SelectList(db.Positions, "PositionID", "PositionName", "PositionCategory", player.PositionID).SelectedValue;
ViewBag.SeriesID_Man = new SelectList(db.Seriess.Where(x => x.GenderID == 0), "SeriesID", "SeriesName", "SeriesCategory", 0).SelectedValue;
ViewBag.SeriesID_Women = new SelectList(db.Seriess.Where(x => x.GenderID == 1), "SeriesID", "SeriesName", "SeriesCategory", 0).SelectedValue;
Session["viewModel"] = viewModel;
Session["player"] = player;
return RedirectToAction("ChoosePlayerAbonnement");
}
Model
In my model class have I created two fields, that is not mapped to the database, the idea here was to save one of the selected values, from the dropdown lists in the view.
[NotMapped]
public int? SeriesID_Man { get; set; }
[NotMapped]
public int? SeriesID_Women { get; set; }
Repossitory
In the repo, I try to insert the value from SeriesID_Man, and SeriesID_Women into database.
SeriesID_Man = player.SeriesID,
SeriesID_Women = player.SeriesID,
can someone tell me what I'm doing wrong? :-)
I have this simple query:
var sample = from training in _db.Trainings
where training.InstructorID == 10
select new { Something = training.Instructor.UserName };
And I pass this to ViewBag.
ViewBag.Sample = sample;
Then I want to access it in my view like this:
#foreach (var item in ViewBag.Sample) {
#item.Something
}
And I get error message 'object' does not contain a definition for 'Something'. If I put there just #item, I get result { Something = SomeUserName }
Thanks for help.
This cannot be done. ViewBag is dynamic and the problem is that the anonymous type is generated as internal. I would recommend you using a view model:
public class Instructor
{
public string Name { get; set; }
}
and then:
public ActionResult Index()
{
var mdoel = from training in _db.Trainings
where training.InstructorID == 10
select new Instructor {
Name = training.Instructor.UserName
};
return View(model);
}
and in the view:
#model IEnumerable<Instructor>
#foreach (var item in ViewBag.Sample) {
#item.Something
}
If you want to send in ViewData For example and don't want to send in model
you could use the same could as in the upper answer
and in the Controller
enter code here
ViewData[Instractor] = from training in _db.Trainings
where training.InstructorID == 10
select new Instructor {
Name = training.Instructor.UserName
};
and in the view you need to cast this to
`IEnumerable<Instructor>`
but to do this you should use
#model IEnumerable<Instructor>
Then you could do something like this
IEnumerable<instructors> Instructors =(IEnumerable<Instructor>)ViewData[Instractor];
then go with foreach
#foreach (var item in Instructors ) {
#item.Something
}
I'm facing problems with a MVC5 Razor web application. I have an authentication page (cshtml) that has an Id and password helper controls:
#model NetInfinity.Middleware.VistaModelos.LoginVistaModelo
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<h1>#Login.Acceso</h1>
<p>
#Html.TextBoxFor(c => c.Id, new { #placeholder = #Login.Usuario, autofocus = "", autocomplete = "off", maxlength = "15", size = "15" })
</p>
<p class="p1">
#Html.PasswordFor(c => c.Clave, new { #placeholder = #Login.Contraseña, maxlength = "20", size = "20" })
#Html.ActionLink(".", "Cambiopwd", null, new { #class = "login-cambiarpwd", id = "Cambiopwd" })
</p>
<p class="login-recordarpwd">#Html.ActionLink(#Login.RecordarPwd, "Recordatoriopwd")</p>
<button type="button" class="login-submit" id="login-submit">#Login.LoginSubmit</button>
}
And the respective Model:
public class LoginVistaModelo
{
public string Id
{
get;
set;
}
[DataType(DataType.Password)]
public string Clave
{
get;
set;
}
public string MensajeError
{
get;
set;
}
}
And Controller Action that validates user is:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginVistaModelo vmUsuario)
{
if (ModelState.IsValid)
{
EntidadesBD backend;
var cache = MemoryCache.Default;
backend = (EntidadesBD)cache.Get("backend");
if (backend == null)
{
backend = new EntidadesBD();
var politica = new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable };
cache.Set("backend", backend, politica);
}
Usuario usuario = vmUsuario.ValidaUsuario();
if (usuario == null)
{
vmUsuario.MensajeError = "error2";
vmUsuario.Id = vmUsuario.Clave = String.Empty; // <--- This not works
ModelState.Clear(); // <-- This not works
}
else
{
}
}
return View(vmUsuario);
}
When Login Action is triggered to validate user and password and error is thrown, I need to clear TextBoxFor value and PasswordFor value, and to achieve this I set model properties Id and Clave to string.empty in Controller, however when page (cshtml) is rendered again, controls keep old values ignoring model changes, not even if ModelState.Clear(). I've heard that HtmlHelpers controls (like .TextBoxFor() etc.) don't bind to model values on Postback, but rather get their value directly out of the POST buffer from ModelState. Please, ¿How can I do to update controls value when they are changed in Model properties?
Thanks
try making the value of model null before returning it to view,
like vmUsuario.id = null, vmUsuario.clave= null ; and thn return the empty model to view
A better approach for this type of problem would be to redirect the user, rather than returning the view. Otherwise you run into the problem that if they press F5 it reposts the data. So simply redirect the user, and use TempData to include your error message. In your Get method, check if TempData contains an error message and display it if it does.
I'm trying to create a select list. I've created it just fine using a collection from my viewmodel that allows me to set each option's value and text with the following code:
#Html.DropDownListFor(model => model.Networks, new SelectList(Model.Networks, "NetworkID", "Name"), new { #class="form-control" })
Model.Networks contains another property called CountryId. I'd like to add an attribute to each option tag so it looks like:
<option value="[NetworkId]" data-countryId="[CountryId]">Canada</option>
Which way should I go about doing this?
You can create a Form Helper class to create a custom drop down list, and create a custom 'selectListItem' class that has an extra property 'itemsHtmlAttributes' of type IDictionary - see below. You may need to play around with the 'id' or 'name' attributes to get the default model binding working. Below is a bit messy, I would suggest using TagBuilder to build the 'select' and 'option' tags:
public class SelectListItemCustom : SelectListItem
{
public IDictionary<string, object> itemsHtmlAttributes { get; set; }
}
public static class FormHelper
{
public static MvcHtmlString DropDownListForCustom(this HtmlHelper htmlHelper, string id, List<SelectListItemCustom> selectListItems)
{
var selectListHtml = "";
foreach (var item in selectListItems)
{
var attributes = new List<string>();
foreach (KeyValuePair<string, string> dictItem in item.itemsHtmlAttributes)
{
attributes.Add(string.Format("{0}='{1}'", dictItem.Key, dictItem.Value));
}
// do this or some better way of tag building
selectListHtml += string.Format(
"<option value='{0}' {1} {2}>{3}</option>", item.Value,item.Selected ? "selected" : string.Empty,string.Join(" ", attributes.ToArray()),item.Text);
}
// do this or some better way of tag building
var html = string.Format("<select id='{0}' name='{0}'>{1}</select>", id, selectListHtml);
return new MvcHtmlString(html);
}
}
VIEW:
#{
var item = new SelectListItemCustom { Selected = true, Value = "123", Text = "Australia", itemsHtmlAttributes = new Dictionary<string, object> { { "countrycode", "au" } } };
var items = new List<SelectListItemCustom> { item };
Html.Raw(Html.DropDownListForCustom("insertIdHere", items))
}
I have a DropDownList that contains the correct items and values when the view is rendered but the selected value is not being saved within the designated entity field Garage. Currently the value being saved and returned is 0 (None) in both create or edit post methods. I'm sure this is something simple but I can't figure it out... Thanks in advance!
The Model Class:
public enum GarageType { None = 0, One = 1, Two = 2, Three = 3, Four = 4 }
public int Garage { get; set; }
[NotMapped]
public GarageType GarageEnumValue
{
get { return (GarageType)Garage; }
set{ Garage = (int)value; }
}
The Control Create and Edit methods both look like this:
var statuses = from Property.GarageType s in Enum.GetValues(typeof(Property.GarageType))
select new { ID = (int)s, Name = s.ToString() };
ViewBag.GarageId = new SelectList(statuses, "ID", "Name", statuses.FirstOrDefault().ID);
Last the View:
#Html.DropDownList("GarageId", String.Empty)
Use the following overload of DropDownList method
#Html.DropDownList("GarageEnumValue", (SelectList)ViewBag.GarageId, String.Empty)
If you have a strongly type model use
#Html.DropDownListFor(m => m.GarageEnumValue, (SelectList)ViewBag.GarageId, String.Empty)
The first argument in both cases should be the property that you are going to bind the list.