If I'm using this viewbag
ViewBag.employee = (from e in db.Employees
select e.FullName).Distinct();
to use in this dropdown list
<div class="form-group">
#Html.LabelFor(model => model.EmployeeID, "EmployeeID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("EmployeeID", new SelectList(ViewBag.employee), "--Select--")
#Html.ValidationMessageFor(model => model.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
Is there a way to concatenate on another detail?
For example EmployeesID so that when you use the dropdown list, the EmployeeID will appear beside their name? I need this feature as some employees might have the same name.
One way to get what you've asked for is to use
select e.FullName + " (" + e.ID + ")"
to concatenate the values together at source in the query.
And remove the Distinct() as it's unnecessary.
P.S. As a broader point, your dropdown list really ought to be using the ID to identify the selected item anyway. So your SelectList should be passed a list of SelectListItem (these can hold both an ID and a display value) instead of a simple list of strings. That way when the form is submitted back to the server you can be certain exactly which employee was selected. You want Razor to render options like <option id="2">Joe Bloggs (2)</option> so that "2" will be the value submitted back to the server. The display value is just for the user and isn't very useful when sending the data back. If you do some searching you'll soon find examples of creating and using SelectListItems.
Related
Basically I have 2 textboxes; I would like whatever the user types into the email textbox to be saved into the name textbox as well.
Basically saving the email address in 2 places. I’m new to MVC any examples would be good, cheers.
#Html.TextBoxFor(m => registerModel.Name, new { #class = "form-control" })
#Html.TextBoxFor(m => registerModel.Email, new { #class = "form-control" })
If you want to save the same values for the both text fields, you can assign same value to both on post function, there is no need for an additional text field.
But if you want to display same value for both text box while typing on one text box. Then try following javascript.
$("#Name").keyup(function(){
var Names = $("#Name").val();
$("#Email").val(Names);
})
I have a dropdownlist for
#Html.DropDownListFor(model => f.MovieID, (SelectList)ViewBag.MoviesList, "--Select One--", htmlAttributes: new { #class = "form-control" })
In the controller I set the ViewBag.MovesList to a SelectList. It is a valid Select List. I'm trying to reuse the same select list for multiple items in a foreach loop. However, when it is rendered the existing MovieID value is not being selected in the drop down list. I have seen many similar questions but none of their root causes I am seeing in mine. Also, based on other questions simimar, this is slightly different then others because it is inside of a loop.
Try something like below:
#Html.DropDownListFor(model => model.MovieID, new SelectList((IEnumerable)ViewBag.MoviesList, "Value", "Text", Model.MovieID), new { #class = "form-control" })
Where Value is what you want to pass to the action invoked and Text is what you want to show in the dropdown.
I am testing this on chrome. I have set chrome to remember user name and passwords. I have a very simple MVC 5 web application where i have login screen and also screen to create user. When user log in, I let chrome save user name and password.
Problem is that when I try to create new user, its not coming user name as blank, but still showing user name that I logged in with.
I want to do in view and not through controller default vault. I tried using below example link on SO, but my code is still not working
how to set default value HTML.EditorFor()
Here is the code that I tried and its not working.
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label" })
<br />
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control", #Value ="" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
</div>
</div>
Please advice what should I do to fix this. You you.
Easiest way around this is to simply change the name of the property in your model from UserName to NewUserName. That way the autofill won't associate autofill entries between the two different fields. Your create and login model are different anyway.
Or, you could also try changing the name of the textbox in your View.
#Html.EditorFor(m => m.UserName, new {htmlAttributes = new { #Name="NewUserName", #id="NewUserName", #class = "form-control", #Value =""}})
You would need to add a parameter in your controller for NewUserName next to your other model parameters.
In HTML5 we can create input fields with custom validation error statements.
For instance:
<input type="text" name="username"
id="username" pattern="[a-zA-Z ]{5,}"
maxlength="30" required />
<div class="validation-messages">
<span data-rule="valueMissing" //FIRST RULE
class="hide">The username is required. </span>
<span data-rule="patternMismatch" //SECOND RULE
class="hide">ust be a series of alpha characters only (min 5, max 30).
</span>
</div>
If user breaks any data rule he gets notification which depends on the broken rule and I look for a way to use them in ASP.NET-MVC.
All HTML5 native errors are:valueMissing, typeMismatch, patternMismatch, tooLong, rangeUnderflow, stepMismatch, value.
In ASP.NET-MVC the Html.EditorFor() method is vastly used. For instance:
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
It generates input fields.
Where and how should I define those native validation errors prompts(for instance patternMismatch seen above)? Should I do it in the EditorFor method or there is a way to define them in the model class?
If you want to validate an input against its type, use EditorFor in the view as you have but then in your model decorate the fields with the DataType attribute like so:
public class ModelTest
{
[DataType(DataType.EmailAddress)]
public string Email {get;set;}
}
You can then go a step futher and use additional parameters to specify various elements of error detailing such as an error message.
[DataType(DataType.EmailAddress,ErrorMessage = "Email is required")]
If you need it to be required use the following attribute
[Required]
If you need to check string length you can use the following attributes as necessary
[StringLength()]
[MinLength()]
[MaxLength()]
For number based validation perhaps try
[Range()]
More often then not, when you are unsure or want to see if some validation exists, just use the Intellisense to browse through possible DataAnnotations
Additional Reading
http://www.asp.net/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-6
https://msdn.microsoft.com/en-us/library/dd901590(VS.95).aspx
I currently have the multiselect working the way I want it with one exception. Preloading previously selected items.
My view looks:
<div class="editor-field">
#Html.LabelFor(model => model.UntaggedPersons)
#Html.ListBoxFor(model => model.PeopleToTag,
new SelectList(Model.CommitteeMembers, "PersonId", "FullName"))
</div>
JS:
$("#PeopleToTag").kendoMultiSelect({ "dataTextField": "FullName", "dataValueField": "PersonId", "placeholder": "Tag or Untag Persons to Action Item" });
PeopleToTag is an IEnumerable<int> int that posts to the controller
CommitteeMembers consists of a persons First, Last, FullName, and PersonId
This works perfectly, I can manipulate who is tagged in the post to the controller.
Now I want to add the functionality of preselecting those that are currently tagged.
How do I add a preselected Value? I have a model with:
model.TaggedPersons consists of a persons First, Last, Fullname, PersonId.
How do I wire up the javascript to display the model.TaggedPersons as the already selected value?
I don't mind using the MVC wrapper approach if it is easier.
I've tried something like:
<div class="editor-field">
#Html.LabelFor(model => model.TaggedPersons)
#(Html.Kendo().MultiSelectFor(model => model.PeopleToTag)
.Name("PeopleToTag")
.Placeholder("These people are Tagged")
.DataTextField("FullName")
.DataValueField("PersonId")
.BindTo(Model.CommitteeMembers)
.Value(Model.TaggedPersons)
)
</div>
However this isn't even rendering a kendo multiselect for me at present. That's the general thought of how I want to approach it though.
Any help is much appreciated!
Change:
DataTextField("FullName") to DataTextField("Text")
DataValueField("PersonId") to DataValueField("Value")
SelectList uses "Text" and "Value", respectively. You already filled the fields of the select list with FullName and PersonId when the selectlist was created.