Generating SelectList with default selected item in MVC - html

I'm trying to generate a selectList with a default selected item in MVC. I assign a selectlist to the viewbag and try to render it in my view and keep getting the below error.
Does anyone know what I might be doing wrong?
Create the list in my controller:
ViewBag.MasterAccountSelect = new SelectList(masterAccountsList, "MasterAccount", "MasterAccount", userSettingsViewModel.MasterAccountName);
Render the SelectList in my view:
<div class="editor-label">
#Html.LabelFor(model => model.MasterAccountSelect, "MasterAccountSelect")
</div>
<div class="editor-field">
#Html.DropDownList("MasterAccountSelect")
#Html.ValidationMessageFor(model => model.MasterAccountSelect)
</div>
I get this error:
Compiler Error Message: CS1061: 'UserSettingsViewModel' does not
contain a definition for 'MasterAccountSelect' and no extension method
'MasterAccountSelect' accepting a first argument of type
'UserSettingsViewModel' could be found (are you missing a using
directive or an assembly reference?)
I also get this error when I

You view model does not have a property named MasterAccountSelect hence the error. From the code you are assigning to ViewBag, you appear to be wanting to bind to a property in your model named MasterAccountName in which case your model should be
public class UserSettingsViewModel
{
[Display(Name = "Master Account Name")]
[Required(ErrorMessage = "Please select a master account name")]
public string MasterAccountName { get; set; }
public SelectList MasterAccountNameList { get; set; }
....
}
Then in the GET method
UserSettingsViewModel model = new UserSettingsViewModel
{
MasterAccountName = ..... ,
MasterAccountNameList = new SelectList(masterAccountsList, "MasterAccount", "MasterAccount")
}
return View(model);
And in the view
<div class="editor-label">
#Html.LabelFor(m => m.MasterAccountName)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.MasterAccountName, Model.MasterAccountNameList, "-Please select-")
#Html.ValidationMessageFor(m => m.MasterAccountName)
</div>
Side note: Since you wanting the options value and display text to be the same (using property MasterAccount), you can also use
MasterAccountNameList = new SelectList(masterAccountsList.Select(x => x.MasterAccount))

try Label instead of LabelFor, You can not use LabelFor strictly type html helper if you don't have property in your model.
<div class="editor-label">
#Html.Label("MasterAccountSelect")
</div>
<div class="editor-field">
#Html.DropDownList("MasterAccountSelect")
#Html.ValidationMessageFor(model => model.MasterAccountSelect)
</div>
One good Suggestion
Whenever you are using Viewbag for filling dropdown, Keep your Viewbag and property name different because it will not auto select your selected value.

Related

How did my ViewBag become populated with data?

I'm working with a Kendo Grid that shows a modal when editing or adding a row. I'm seeking to modify the modal and add another dropdown list to it. The one thing I'm totally confused about at the moment is that the cshtml for the modal refers to the ViewBag to provide the source data for the dropdownlists, but I can't find anywhere in the entire solution where any code (anywhere) populates the ViewBag with the properties the modal uses.
Before I started modifying, the cshtml had:
#Html.Kendo().DropDownListFor(model => model.Status).BindTo(ViewBag.Statuses).DataTextField("Name").DataValueField("Value").OptionLabel("Please Select")
^^^^^^^^^^^^^^^^
The debugger says this is valid; the ViewBag does contain a .Statuses and it is loaded with data, but I've no idea how this thing came to be in the ViewBag. The only place the controller refers to the viewbag is in setting the .Title
Here's cshtml for the modal:
#model ModalModel
#Html.HiddenFor(model => model.Id)
<!-- this is the new one -->
<div class="editor-group">
<div class="editor-label">
#Html.LabelFor(model => model.ProjectId)
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.ProjectId).BindTo(ViewBag.ProjectId_Data).OptionLabel("Please Select")
#Html.ValidationMessageFor(model => model.ProjectId)
</div>
</div>
<!-- existing one. Needs DataTextField and DataValueField because model.Statuses is not an IEnumerable<SelectListItem>, its a custom collection of c# enum name/value representation -->
<div class="editor-group">
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.Status).BindTo(ViewBag.Statuses).DataTextField("Name").DataValueField("Value").OptionLabel("Please Select")
#Html.ValidationMessageFor(model => model.Status)
</div>
</div>
Here's a snip of the cshtml for the main grid and some periphery stuff:
#model GridModel
<h3>#ViewBag.Title</h3>
#{
var projectListItems = Model.Projects.Select(e => new SelectListItem { Value = e.Id.ToString(), Text = e.Name });
var activityListItems = Model.Activities.Select(e => new SelectListItem { Value = e.Id.ToString(), Text = e.PrivateName });
}
#(Html.Kendo().Grid<UsageModel>()
.Name("MainGrid")
.Columns(cfg =>
{
cfg.Bound(e => e.DateUsed).ClientTemplate("#= kendo.toString(DateUsed, \"d\") #");
cfg.ForeignKey(e => e.ProjectId, projectListItems, "Value", "Text").Title("Project name").Width(150);
cfg.ForeignKey(e => e.ActivityId, activityListItems, "Value", "Text").Title("Activity name").Width(150);
cfg.ForeignKey(e => e.Status, Model.Statuses, "Value", "Name");
cfg.Command(cmd => { cmd.Edit(); cmd.Destroy().HtmlAttributes(new { style = "visibility:hidden" }); }).Width(80);
})
.Pageable()
...
The 4 items in the ViewBag are:
ProjectId_Data (IEnumerable<SelectListItem>)
ActivityId_Data (IEnumerable<SelectListItem>)
Status_Data (IEnumerable<SelectListItem>)
Statuses (IEnumerable<a custom internal type used for expanding enums into name/value strings>)
Am I correct in assuming that Kendo added these things to the viewbag as part of the data binding process on the main grid? The rendering of the grid to page occurs before the processing of the modal..
Please give (IEnumerable) inside BindTo() for casting and try
#using Kendo.Mvc.UI
#using System.Collections
#Html.Kendo().DropDownListFor(model => model.Status).BindTo((IEnumerable)ViewBag.Statuses).DataTextField("Name").DataValueField("Value").OptionLabel("Please Select")

Modifying dropdown menu - Autogenerated MVC / CRUD code

I am new to Entity Framework/MVC and need to know how to modify a dropdown menu autogenerated by Visual Studio. I imagine it should be pretty simple, but I have not been able to figure it out. I have used the database-first approach and have the two following tables in my database:
public partial class RestaurantRating
{
public int RestaurantRatingId { get; set; }
public int RestaurantRatingScore { get; set; }
}
public partial class RestaurantType
{
public int RestaurantTypeId { get; set; }
public string RestaurantTypeDesc { get; set; }
}
I removed the extra details, but basically one of them will store restaurant ratings (the rating being an integer) and the other one will store restaurant types (what type of food they serve). The only really difference between the two is that the rating is an integer and they type description is a string.
Visual Studio autogenerated code for the CRUD operations for these and other tables. The HTML code in Create.cshtml for these two tables is as follows:
<div class="form-group">
#Html.LabelFor(model => model.RetaurantTypeId, "RetaurantTypeId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("RetaurantTypeId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.RestaurantTypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RestaurantRatingId, "RestaurantRatingId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("RestaurantRatingId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>
And the ViewBag information for these two tables in the Create Action result in the controller is the following:
ViewBag.RestaurantRatingId = new SelectList(db.RestaurantRating, "RestaurantRatingId", "RestaurantRatingId");
ViewBag.RestaurantTypeId = new SelectList(db.RestaurantType, "RestaurantTypeId", "RestaurantTypeDesc");
The problems and expected results are the following:
The dropdown menu for RestaurantType works as expected. It simply loads the different types into a dropdown menu and allows the user to select one of them. However, the RestaurantRating will load the RatingIds instead of the descriptions, which is what I need. I have tried changing the viewbag without success.
The HTML code automatically selects the first value for the dropdown menus, but it is possible to save NULL values to the database for these fields. How can I add an empty default value for the dropdown menus above, so that if the user selects the empty value (or does not touch the dropdown menu) a NULL value will be pushed to the database?
Any help is greatly appreciated. I will be happy to provide any additional code/information. Thank you so much!
You Just need to add an option label to your dropdown like this:-
#Html.DropDownList("RetaurantTypeId", null,"optionLable goes Here", htmlAttributes: new { #class = "form-control" })
and make sure on the other side that you are binding it to a nullable model property so the model binder will be able to set the model property value to Null.
hope this answer your question.

Dropdownlistfor will not show the correct selection

I have three dropdownlistfor in a loop that do not show the correct value from the DB. They always default to the first entry. I have checked and double checked the DB and verified that it should be the second one in the list. The list is also created correctly. What am I missing?
#foreach (CustomerMeasurementProfile oProfile in Model.Customer.CustomerMeasurementProfiles.Where(m => m.DeletedDate == null))
{
<div class="valuesforoneprofile form-group form-group-tight col-md-2">
<div class="col-md-11" >
#Html.Hidden(string.Format("Customer.CustomerMeasurementProfiles[{0}].Id", i), oProfile.Id)
#Html.Hidden(string.Format("Customer.CustomerMeasurementProfiles[{0}].CustomerId", i), oProfile.CustomerId)
#Html.TextBox(string.Format("Customer.CustomerMeasurementProfiles[{0}].Name", i), oProfile.Name, new { #class = "form-control input-sm" })
</div>
<div class="col-md-11" style="text-align:center">
#Html.CheckBox(string.Format("DeleteProfiles[{0}]", i), Model.DeleteProfiles[i])
</div>
<div class="col-md-11" style="padding-top:4px;">
#Html.DropDownListFor(m => oProfile.BodyTypeShoulderId, new SelectList(Model.BodyTypeShoulders, "Id", "Name"), new { #class = "form-control input-sm-select" })
</div>
<div class="col-md-11" style="padding-top:4px;">
#Html.DropDownListFor(m => oProfile.BodyTypePostureId, new SelectList(Model.BodyTypePosture, "Id", "Name"), new { #class = "form-control input-sm-select" })
</div>
<div class="col-md-11" style="padding-top:4px;">
#Html.DropDownListFor(m => oProfile.BodyTypeChestId, new SelectList(Model.BodyTypeChest, "Id", "Name"), new { #class = "form-control input-sm-select" })
</div>
If you want to set the selected value that is coming in Model. You need to do it like this:
#Html.DropDownListFor(m => oProfile.BodyTypeShoulderId,
new SelectList(Model.BodyTypeShoulders,
"Id",
"Name",
oProfile.BodyTypeShoulderId),
new { #class = "form-control input-sm-select" })
The above code will set the dropdown selected value to whatever is in the current Model object BodyTypeShoulderId
The first argument of DropDownListFor tells that on form post drop down selected value will be mapped with the Model property which is set there (we are passing m => oProfile.BodyTypeShoulderId) but this not sets selected Value.
For setting selected value you have to pass SelectList fourth parameter using this overload of SelectList class which is object selectedValue
Unfortunately #Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. For a single object
#Html.DropDownListFor(m => oProfile.BodyTypeShoulderId, new SelectList(Model.BodyTypeShoulders, "Id", "Name"))
would work fine (if the value of BodyTypeShoulderId matches the value of one of the options, then that option would be selected). Ehsan has shown a work around when using it in a loop, however you have a few other issues in you code, not the least is that many of your properties will not post back correctly to a collection because your using a foreach loop rather than a for loop (which is generating duplicate name and id attributes). Your also generating a new SelectList in each iteration of the loop which is not very efficient.
You can solve both these and the dropdown selection issue by using an EditorTemplate. Assuming property CustomerMeasurementProfiles is typeof CustomerMeasurementProfiles, then
CustomerMeasurementProfiles.cshtml (add this to Views/Shared/EditorTemplates or Views/YourController/EditorTemplates)
#model CustomerMeasurementProfiles
#Html.HiddenFor(m => m.ID)
#Html.HiddenFor(m => m.CustomerId)
....
#Html.DropDownListFor(m => m.BodyTypeShoulderId, (SelectList)ViewData["shoulders"])
....
In the view model, add properties for the SelectList's and filtered collection of the items to display
IEnumerable<CustomerMeasurementProfiles> ActiveCustomerMeasurementProfiles { get; set; }
public SelectList BodyTypeShoulderList { get; set; }
....
and assign those values in the controller
Then in the main view
#using (Html.BeginForm())
{
...
#Html.EditorFor(m => m.ActiveCustomerMeasurementProfiles, new { shoulders = Model.BodyTypeShoulderList })
...
Using #Html.EditorFor() with a collection will correctly name the controls (and correctly select the right options) and on post back, ActiveCustomerMeasurementProfiles will now be correctly populated with all its properties.

HtmlHelper inside HtmlHelper

Is it possible to make a HtmlHelper for parts where another htmlherlper is already used.
like in this case:
<div class="control-group">
#Html.LabelFor(model => model.cLinks.Link2Privates)
<div class="controls">
#Html.TextBoxFor(model => model.cLinks.Link2Privates, new { #class = " span7"})
#Html.ValidationMessageFor(model => model.cLinks.Link2Privates)
</div>
</div>
I'm assuming you simply want a helper that will generate all this information for you. While it's technically possible to create a custom helper that will do just that, it's actually better to use editor templates:
Views\Shared\EditorTemplates\BootstrapControlGroup.cshtml
<div class="control-group">
#Html.Label("")
<div class="controls">
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { #class = " span7"})
#Html.ValidationMessage("")
</div>
</div>
Form
#Html.EditorFor(m => m.cLinks.Link2Privates, "BootstrapControlGroup")
That basically says to use this template to render the "editor" for this property. If you don't want to have to specify the template name, there's other ways. You can decorate your property with the UIHint attribute:
[UIHint("BoostrapControlGroup")]
public string Link2Privates { get; set; }
Or you can rely on a particular C# type or DataType. For example, if you wanted all strings to be handled this way, you could name that template String.cshtml instead and then just do:
#Html.EditorFor(m => m.cLinks.Link2Privates)
Razor would see that it was a string and use the String.cshtml editor template automatically if it existed. You can also use the DataType attribute, for example:
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
And, then create a Views\Shared\EditorTemplates\EmailAddress.cshtml template. Razor will use this template, then, any time you call Html.EditorFor for this property.
I have created a HtmlHelper extension library that works well with Twitter Bootstrap scenarios.
http://buildmvc.codeplex.com
There's even a HtmlHelper add-on for Twitter Bootstrap Form Groups:
https://www.nuget.org/packages/Build.Mvc.TwitterBootstrap
#using ( Html.BuildForm().Begin(FormRenderStyle.Horizontal) )
{
Html.UpdateFormBuilderContext(ctx =>
{
ctx.RenderValidationMessages = true;
});
<fieldset>
<legend>User Information</legend>
#Html.BuildTextBoxGroupFor(m => m.FirstName, b=> b.TextBox(t=> t.Autofocus()))
#Html.BuildTextBoxGroupFor(m => m.Nickname)
#Html.BuildTextBoxGroupFor(m => m.LastName)
</fieldset>
}
Note: The library expects you to be using TwitterBootstrap > v3. The example above has version 2.3.2 class names.

Rendering a different view after the user is logged In

I am creating a web application in MVC 4. How do we create a different view and render it based on if user is logged in or not? I am not sure if I am asking the right question since I am new to programming. I have looked this online but haven't found any resource that guides a beginner to do it. I'm pretty sure this is done in the controller but my question is how to tell the controller to render a different view after checking that the user is logged in. However, if there is some other obvious and efficient way of doing this then I would greatly appreciate if someone took the time to answer this question.
there's an override when you do return View()
return View("myView", myModel");
for example
public ActionResult Index()
{
if(User.Identity.IsAuthenticated)
return View("GoodUser");
return View("BadUser");
}
But if you're new, I would suggest 2 things:
see the hole online curse that is available for free in http://www.asp.net/mvc (right side where it says "Essential Videos")
create an MVC3 project and see how they do it as it's comes already with Membership
You can use Forms Authentication.
ViewModel:
public class LogIN
{
[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
}
Repository:
public class LogInRepository
{
public bool CheckUser(string UserName, string Password)
{
//Query the database here and return true or false depending on the username and the password
}
}
Controller:
[HttpPost]
public ActionResult LogOn(LogIN model, string returnUrl)
{
if (ModelState.IsValid)
{
LogInRepository rep = new LogInRepository();
string UserRole = string.Empty;
if (rep.CheckUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName);
if (!string.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
else
return Redirect(FormsAuthentication.DefaultUrl);
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Account LogIn</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
Web.config settings:
<authentication mode="Forms">
<forms loginUrl="~/Test/LogOn" timeout="2880" defaultUrl="~/Test/Index" />
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
If the User is not logged on user will be redirected to LogOn view and if logged in will redirect to Index view.