How to get default selection into selectlist MVC - asp.net-mvc-4

I need to use dropdownlist into razor and related object into model object.
I want to keep default selected value for the object but it did not work out.
Can any one suggest me what should be the best way to achieve this - what to keep into DTO property and controller action and razor syntax.
Below is my current stuff:
public class StateDTO
{
public int ID { get; set; }
public string Name { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name", Order = 2)]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password", Order = 3)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password", Order = 4)]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Email Address", Order = 1)]
[DataType(DataType.EmailAddress)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Please enter value")]
public string Email { get; set; }
public IEnumerable<SelectListItem> States { get; set; }
public SelectListItem State { get; set; }
}
public ActionResult Register()
{
RegisterModel r = new RegisterModel();
IList<StateDTO> s = new List<StateDTO>();
s.Add(new StateDTO() { ID = 1, Name = "CA" });
s.Add(new StateDTO() { ID = 2, Name = "LA" });
s.Add(new StateDTO() { ID = 3, Name = "AR" });
r.State = new SelectListItem() { Text = s[2].Name, Value = s[2].ID.ToString(), Selected = true };
r.States = new SelectList(s, "ID", "Name",r.State);
return View(r);
}
View contains below related stuff:
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.State, Model.States)
#Html.ValidationMessageFor(model => model.State)
</div>
Please suggest me what should I change into Model object, controller and razor view to achieve default selection of dropdown list... any best way.
Thank You

I have modified the stuff as follow the below link and it worked out.
dropdownlist set selected value in MVC3 Razor
In model, changed the property type as follow:
public IEnumerable<SelectListItem> States { get; set; }
public int State { get; set; }
Controller action:
IList<StateDTO> s = new List<StateDTO>();
s.Add(new StateDTO() { ID = 1, Name = "CA" });
s.Add(new StateDTO() { ID = 2, Name = "LA" });
s.Add(new StateDTO() { ID = 3, Name = "AR" });
r.State = 3;
r.States = new SelectList(s, "ID", "Name",3);
View is as follow:
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.State, Model.States)
#Html.ValidationMessageFor(model => model.State)
</div>
It works...got default selection.
Thank you

Related

Blazor EditForm missing Email and Phone?

Is there a validator for Emails and Phone # in EditForm like there is in Form (e.g.) "tel" for phone and "email" for emails.
Even though they test for formatting not existence of phone and email.
Hy,
What i did was ; create a public class and link this to the editform.
Using Regex expressions you can create your own validation.
public class RegisterAccountModel
{
[Required(AllowEmptyStrings = false, ErrorMessage = "Email adres Missing")]
[EmailAddress(ErrorMessage = "Unvalid Email Address")]
public string Email { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Paswoord Missing")]
[DataType(DataType.Password)]
[StringLength(100)] //, ErrorMessage = "Paswoord dient minstens {2} characters te bevatten waaronder minstens één nummer.", MinimumLength = 6)]
[Display(Name = "Paswoord")]
[RegularExpression("^()(?=.*[\\d])(?=.*[a-z])(?=.*[a-zA-Z]).{6,}$", ErrorMessage = "Min 6 characters and 1 capital letter.")]
public string Password { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Paswoord not Matching")]
[Compare(nameof(Password), ErrorMessage = "Paswoord not Matching")]
public string ConfirmPassword { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Company Is Empty")]
public string Bedrijfsnaam { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Name is empty)]
public string Naam { get; set; }
}
When you want to use this class in your edit form you can do :
<EditForm Context="NewUser" OnSubmit="FormSubmitted" Model="registerAccountModel">
<div class="DataValidationRemark">#RegisterRemarks</div>
<DataAnnotationsValidator />
<ValidationSummary />
<table>
<tr>
<td><p class="label">Email:</p></td>
<td><p><InputText #bind-Value="registerAccountModel.Email" /></p></td>
</tr>
<tr>
<td><p class="label">#lblPassword :</p></td>
<td><p><input type="password" #bind-value="registerAccountModel.Password" /</p></td>
</tr>
</EditForm>
Regarding the submit : This needs to be on your razor page. or code behind file.
#code {
private RegisterAccountModel registerAccountModel = new RegisterAccountModel();
public void FormSubmitted(EditContext editContext)
{
isValidated = editContext.Validate();
if (isValidated)
{
Task.Run(() => RegisterUser());
}
}
Regarding the register user : still on the same razor page
private async Task RegisterUser()
{
//If the form validation is done
if (isValidated)
{
var result = await userManager.CreateAsync(new IdentityUser { UserName = registerAccountModel.Email, Email = registerAccountModel.Email, EmailConfirmed = false }, registerAccountModel.Password);
if (result.Succeeded)
{
//DO STUFF
}
}
}
}
Let me know if it worked for you, or if you got stuck.
Regards,
Mathias

Creating HTML table using Asp.net MVC Model

I am trying to create a dynamic table using MVC Model. This is my Model.
public class PrescriptionEditModel
{
[Required]
public Guid Id { get; set; }
[Required]
[Display(Name = "Medicine List")]
public List<PrescriptionMedicineModel> PrescriptionList { get; set; }
}
public class PrescriptionMedicineModel
{
[Required]
public Guid Id { get; set; }
[Required]
[Display(Name = "Medicine")]
public Guid MedicineId { get; set; }
[Required]
[Display(Name = "Prescription Duration")]
public Guid PrescriptionDurationId { get; set; }
public string NumberOf { get; set; }
}
And My Controller code is
public ActionResult Create()
{
ViewBag.PatientId = new SelectList(db.Patients.Where(h => h.HospitalId == hp.HospitalId), "Id", "FirstName");
ViewBag.MedicineId = new SelectList(db.Medicines.Where(h => h.HospitalId == hp.HospitalId), "Id", "Name");
ViewBag.PrescriptionFrequencyId = new SelectList(db.PrescriptionFrequencies.Where(h => h.HospitalId == hp.HospitalId), "Id", "Name");
PrescriptionMedicineModel prescription = new PrescriptionMedicineModel()
{
MedicineId = Guid.Empty,
PrescriptionDurationId = Guid.Empty,
PrescriptionFrequencyId = Guid.Empty,
PrescriptionWhentoTakeId = Guid.Empty
};
List<PrescriptionMedicineModel> newPrescriptionList = new List<PrescriptionMedicineModel>();
newPrescriptionList.Add(prescription);
PrescriptionEditModel newModel = new PrescriptionEditModel()
{
CaseHistory = null,
DoctorName =null,
HospitalId = hp.HospitalId,
PatientId = Guid.Empty,
PrescriptionDate = null,
PrescriptionList = newPrescriptionList
};
return View(newModel);
}
And My View is
<table class="table table-hover">
<thead>
<tr>
<th>Medicine Name</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
#for (var i = 0; i < Model.PrescriptionList.Count; i++)
{
<tr>
<td>#Html.DropDownListFor(m => Model.PrescriptionList[i].MedicineId, new SelectList(ViewBag.MedicineId, "Id", "Name"))</td>
<td>#Html.DropDownListFor(m => Model.PrescriptionList[i].PrescriptionDurationId, new SelectList(ViewBag.PrescriptionFrequencyId, "Id", "Name"))</td>
</tr>
}
</tbody>
This is giving an error saying "DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Id'.]".
I am trying to create list of medicine with list of items to allow the users edit the details of the medicine. User has to be given the ability to edit the items.
The DropDownListFor is not binding the items to the dropdown.
Any thoughts
Here is an example, I believe your Id and Name fields don't match the model, see how my model has these two properties:
View:
#model XYZ.Models.Adviser
<div class="form-">
<label asp-for="PracticeId" class="control-label">Practice</label>
#Html.DropDownList("PracticeId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.PracticeId)
</div>
Controller:
private void PopulatePracticesDropDownList(object selectedPractice = null)
{
var practicesQuery = from d in _context.Practice
.GroupBy(a => a.Name)
.Select(grp => grp.First())
orderby d.Name
select d;
ViewBag.PracticeId = new SelectList(practicesQuery, "ID", "Name", selectedPractice);
}
Model, it has properties ID and Name:
public class Practice
{
public int ID { get; set; }
[Required]
[Display(Name = "Practice Name")]
public string Name { get; set; }
}
public class Adviser
{
public int ID { get; set; }
[Required]
[Display(Name = "Adviser Name")]
public string Name { get; set; }
[Required]
public int PracticeId { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public string Practice { get; set; }
}

Model properties are null after submit

I have this model:
public partial class Group
{
public Group()
{
this.ParameterGroup = new HashSet<ParameterGroup>();
}
public string GroupId { get; set; }
public string Responsibility { get; set; }
public virtual Text GroupDescText { get; set; }
public virtual Text GroupNameText { get; set; }
public virtual ICollection<ParameterGroup> ParameterGroup { get; set; }
}
public partial class Text
{
public Text()
{
this.ParamName = new HashSet<Parameter>();
this.ParamDesc = new HashSet<Parameter>();
this.EnumElemName = new HashSet<EnumElem>();
this.IoDeviceInfoText = new HashSet<IoDeviceInfo>();
this.IoCatText = new HashSet<IoDeviceInfo>();
this.GroupDesc = new HashSet<Group>();
this.GroupName = new HashSet<Group>();
this.Type = new HashSet<Type>();
this.ParamDispPath = new HashSet<Parameter>();
this.EnumElemText = new HashSet<EnumElem>();
this.TextValue = new HashSet<TextValue>();
}
public string TextId { get; set; }
public string XmlId { get; set; }
public virtual ICollection<Parameter> ParamName { get; set; }
public virtual ICollection<Parameter> ParamDesc { get; set; }
public virtual ICollection<EnumElem> EnumElemName { get; set; }
public virtual ICollection<IoDeviceInfo> IoDeviceInfoText { get; set; }
public virtual ICollection<IoDeviceInfo> IoCatText { get; set; }
public virtual ICollection<Group> GroupDesc { get; set; }
public virtual ICollection<Group> GroupName { get; set; }
public virtual ICollection<Type> Type { get; set; }
public virtual ICollection<Parameter> ParamDispPath { get; set; }
public virtual ICollection<EnumElem> EnumElemText { get; set; }
public virtual ICollection<TextValue> TextValue { get; set; }
}
This is my Controller:
public class GroupController : Controller
{
// GET: Group
public ActionResult Index()
{
return PartialView("Index", GroupModel.Instance.getGroups());
}
public ActionResult Edit(string id)
{
Group group = KebaContext.SessionBasedContext().GroupSet.Where(g => g.GroupId == id).FirstOrDefault();
List<Language> langs = KebaContext.SessionBasedContext().LanguageSet.ToList();
foreach(Language l in langs)
{
if(group.GroupDescText == null)
{
group.GroupDescText = new Text();
TextValue value = new TextValue();
value.TextId = Guid.NewGuid().ToString("N");
value.LangId = l.LangId;
value.Value = "";
group.GroupDescText.TextValue.Add(value);
}
if (group.GroupNameText == null)
{
group.GroupNameText = new Text();
TextValue value = new TextValue();
value.TextId = Guid.NewGuid().ToString("N");
value.LangId = l.LangId;
value.Value = "";
group.GroupNameText.TextValue.Add(value);
}
if (group.GroupDescText != null && group.GroupDescText.TextValue.Where(x => x.LangId == l.LangId).FirstOrDefault() == null) //just one lang is available
{
TextValue value = new TextValue();
value.TextId = group.GroupDescText.TextValue.First().TextId;
value.LangId = l.LangId;
value.Value = "";
group.GroupDescText.TextValue.Add(value);
}
if (group.GroupNameText != null && group.GroupNameText.TextValue.Where(x => x.LangId == l.LangId).FirstOrDefault() == null) //just one lang is available
{
TextValue value = new TextValue();
value.TextId = group.GroupNameText.TextValue.First().TextId;
value.LangId = l.LangId;
value.Value = "";
group.GroupNameText.TextValue.Add(value);
}
}
return View(group);
}
[HttpPost]
public ActionResult Edit(Group xyz)
{
return RedirectToAction("Index", "Types");
}
}
This is my View:
#using System.Web.Mvc.Html;
#model Keba.Data.EF.Group
#{
ViewBag.Title = "Group Editing";
}
<h2>Edit Group</h2>
<div id="groupEdit">
#using (Html.BeginForm("Edit", "Group", FormMethod.Post))
{
#Html.HiddenFor(model => model.GroupId);
<table class="userEditAddTable">
<tr><th>Responsibility</th><td>#Html.EditorFor(model => model.Responsibility)</td></tr>
#foreach (var name in Model.GroupNameText.TextValue)
{
#Html.HiddenFor(model => name.LangId)
#Html.HiddenFor(model => name.Value)
<tr><th>GroupNameText(#Html.DisplayFor(model => name.LangId))</th><td> #Html.TextBoxFor(model => name.Value)</td></tr>;
}
#foreach (var desc in Model.GroupDescText.TextValue)
{
#Html.HiddenFor(model => desc.LangId)
#Html.HiddenFor(model => desc.Value)
<tr><th>GroupDescText(#Html.DisplayFor(model => desc.LangId))</th><td> #Html.TextBoxFor(model => desc.Value)</td></tr>;
}
</table>
<br />
<div id="buttons">
<input name="Save" type="submit" value="Save" class="button" />
<input name="Cancel" type="submit" value="Cancel" class="button" />
</div>
}
</div>
Problem:
If I try to change the value of a Text in the group model e.g. GroupNameText.TextValue.Value send it to the controller (submit). The properties GroupNameText and GroupDescText are null.
I have also tried the solution with propertybinding ([Bind(Include = "GroupDescText,GroupNameText")] Group xyz) which also doesn't work
First, remember that only properties that are posted (i.e. have a form input element representing them) will be populated.
Second, the names of the input elements must match up to what the model binder expects on post, or it will discard the values, as it won't know what to do with them. In particular, with enumerables, this means you need to use for loops rather than foreach, so that Razor can create the right name binding:
#for (var i = 0; i < Model.GroupNameText.TextValue; i++)
{
#Html.HiddenFor(m => m.GroupNameText.TextValue[i].LangId)
#Html.HiddenFor(m => m.GroupNameText.TextValue[i].Value)
...
}
That will result in a name attribute like GroupNameText.TextValue[0].LangId, which the model binder should be able to bind appropriately, whereas your field names are currently just LangId, which is meaningless on post.
Have a look at this similar to your approach is to have a list in the view, you might need to have partials.

Dropdown List MVC 4 error

I am trying to get a drop down list to work but its not working for me. This application is mainly a festival based application where you can add a festival along with your events. The error I am getting is on line:
#Html.DropDownList("towns", (IEnumerable<SelectListItem>)ViewData["Town"], new{#class = "form-control", #style="width:250px" })
This is the error I get:
There is no ViewData item of type 'IEnumerable' that has the key 'towns'.
Create.cshtml
<div class="form-group">
#Html.LabelFor(model => model.FestivalTown, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("towns", (IEnumerable<SelectListItem>)ViewData["Town"], new{#class = "form-control", #style="width:250px" })
#Html.ValidationMessageFor(model => model.FestivalTown)
</div>
#*#Html.Partial("ddlFestivalCounty");*#
</div>
Controller.cshtml
//Get
List<SelectListItem> Towns = new List<SelectListItem>();
Towns.Add(new SelectListItem { Text = "Please select your Town", Value = "SelectTown" });
var towns = (from t in db.Towns select t).ToArray();
for (int i = 0; i < towns.Length; i++)
{
Towns.Add(new SelectListItem
{
Text = towns[i].Name,
Value = towns[i].Name.ToString(),
Selected = (towns[i].ID == 0)
});
}
ViewData["Town"] = Towns;
//Post
festival.FestivalTown.Town = collection["Town"];
Model.cs
public class Festival
{
public int FestivalId { get; set; }
[Required]
[Display(Name = "Festival Name"), StringLength(100)]
public string FestivalName { get; set; }
[Required]
[Display(Name = "Start Date"), DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Required]
[Display(Name = "End Date"), DataType(DataType.Date)]
public DateTime EndDate { get; set; }
[Required]
[Display(Name = "County")]
public virtual County FestivalCounty { get; set; }
[Display(Name = "Festival Location")]
public DbGeography Location { get; set; }
[Required]
[Display(Name = "Town")]
public virtual Town FestivalTown { get; set; }
[Required]
[Display(Name = "Festival Type")]
public virtual FestivalType FType { get; set; }
public UserProfile UserId { get; set; }
}
public class Town
{
public int ID { get; set; }
[Display(Name = "Town")]
public string Name { get; set; }
}
I suspect that this error occurs when you submit the form to the [HttpPost] action and not when you are rendering the form, right? And this action renders the same view containing the dropdown, right? And inside this [HttpPost] action you forgot to populate the ViewData["Town"] value the same way you did in your HttpGet action, right?
So, go ahead and populate this property the same way you did in your GET action. When you submit the form to your [HttpPost] action, only the selected value is sent to the controller. So you need to repopulate the collection values if you intend to redisplay the same view, because this view renders a dropdown which is attempting to bind its values from ViewData["Town"].
And here's what I mean in terms of code:
[HttpPost]
public ActionResult SomeAction(Festival model)
{
... bla bla bla
// don't forget to repopulate the ViewData["Town"] value the same way you did in your GET action
// if you intend to redisplay the same view, otherwise the dropdown has no way of getting
// its values
ViewData["Town"] = ... same stuff as in your GET action
return View(model);
}
And all this being said, I would more than strongly recommend you using view models instead of this ViewData/ViewBag weakly typed stuff. Not only that your code will become much more clean, but even the error messages will start making sense.

How to save selected radio button value in MVC4

I am working in MVC4.In this I am using the following code for radio buttons :
Model :
public class PlatInspHistoryModels
{
public List<RadioButtonItem> RadioButtonList { get; set; }
public string SelectedRadioButton { get; set; }
}
public class RadioButtonItem
{
public string Name { get; set; }
public bool Selected { get; set; }
public string Value { get; set; }
public bool Visible { get; set; }
}
controller :
public ActionResult Index()
{
var viewModel = new PlatInspHistoryModels
{
RadioButtonList = new List<RadioButtonItem>
{
new RadioButtonItem
{
Name = "Topside", Value = "T",Selected = true,Visible = true
},
new RadioButtonItem
{
Name="Underwater", Value = "U",Selected = false,Visible = true
}
}
};
return View(viewModel);
}
View :
#using (Html.BeginForm("Index", "PlatInspHistory", FormMethod.Post, new { id = "form" }))
{
<table cellpadding="4" cellspacing="4">
<tr>
<td>
foreach (Cairs2.Models.RadioButtonItem item in Model.RadioButtonList)
{
#Html.DisplayFor(i => item.Name)
#Html.RadioButton("PlatInspHistoryModels.SelectedRadioButton", item.Value, item.Selected, new { #class = "formCheckbox", tabindex = "1" })
}
</td>
</tr>
</table>
}
Problem :
From the above code I am able to bind radio buttons as a list. But how I can get selected radio value on save event given below :
[HttpPost]
public ActionResult Index(PlatInspHistoryModels model)
{
}
Replace your foreach loop with this with a for loop and use strongly typed helpers:
for (var i = 0; i < Model.RadioButtonList.Count; i++)
{
#Html.DisplayFor(x => x.RadioButtonList[i].Name)
#Html.HiddenFor(x => x.RadioButtonList[i].Name)
#Html.RadioButtonFor(x => x.SelectedRadioButton, Model.RadioButtonList[i].Value, new { #class = "formCheckbox", tabindex = "1" })
}
I am working in MVC5, i have mcqs questions in the form of radio buttons that are randomly fetched from database here is my`[Table("Mcqs")]
public class MCQS
{ [Key]
public int Qid { get; set; }
[Required(ErrorMessage = "Please Enter Skill.")]
public string Skill { get; set; }
[Required(ErrorMessage = "Please Enter Question.")]
public string Question { get; set; }
[Required(ErrorMessage = "Please Enter Level.")]
public string Levels { get; set; }
[Required(ErrorMessage = "Please Enter Options.")]
public string AnsOpt1 { get; set; }
[Required(ErrorMessage = "Please Enter Options.")]
public string AnsOpt2 { get; set; }
[Required(ErrorMessage = "Please Enter Options.")]
public string AnsOpt3 { get; set; }
[Required(ErrorMessage = "Please Enter Options.")]
public string AnsOpt4 { get; set; }
[Required(ErrorMessage = "Please Set Weightage.")]
and controller
public ActionResult Index()
{ return View((from a in ne.Mcqs orderby Guid.NewGuid() select a).Take(2).ToList()); }
and view
#foreach (var item in Model)
{<tr>
<td>
#Html.DisplayFor(modelItem=>item.Qid)</td>
<td> #Html.DisplayFor(modelItem => item.Question)</td> <td>
#Html.RadioButton("skillsq1", new { id = "1"}).
#Html.DisplayFor(modelItem => item.AnsOpt1)</td><td>
#Html.RadioButton("skillsq1", new { id = "2"})
#Html.DisplayFor(modelItem => item.AnsOpt2) </td><td>
#Html.RadioButton("skillsq1", new { id = "3" })
#Html.DisplayFor(modelItem => item.AnsOpt3) </td> <td>
#Html.RadioButton("skillsq1", new { id = "4" })
#Html.DisplayFor(modelItem => item.AnsOpt4) </td> </tr>}
i want to ask that how i get the value of the checked radio button of the shuffled question