MVC set default value EditorFor() to blank - asp.net-mvc

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.

Related

ASP>NET MVC concatenate two details onto dropdown list

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.

How to use HTML5 native validation rules for text input fields in ASP.NET-MVC 5.2?

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

autocomplete=off not working in mvc 5

I am trying not to generate autocomplete in browser for that I am trying this
#Html.TextBoxFor(
model => model.UserName,
new { #class = "form-control", autocomplete = "off" })
#Html.ValidationMessageFor(m => m.UserName, "", new { #class = "text-danger" })
which generate HTML like this
<input type="text" value="" name="UserName" id="UserName" data-val-required="User name is required." data-val="true" class="form-control" autocomplete="off">
In other views I have use the same and it is working fine. but in login view autocomplete="off" not working. for doing so I have clear model state like this in controller
ModelState.Remove("UserName");
reference taken from the following sites
How to Turn Off Form Autocompletion
Disable autocomplete on html helper textbox in MVC
How to disable autocomplete in MVC Html Helper
Remove browser autocompletion in MVC
I still wonder what is wrong in my code? Your suggestion means a lot to me.
As per Bharat's answer it actually, the issue is not of the autocomplete,
the issue comes from the browser's saved logins.
but we can overcome this without going to clear saved passwords of the browser.
As per my intention, all browsers doing similar duties that the field before the password is assumed as Username and it uses the last logged in data will be pasted automatically even if we do autocomplete="off".
The solution is to make the password's field autocomplete="new-password", but this will work only in HTML5 or above supported browsers only...
The issue comes from the browser's saved logins.
When these issue arise at my side, i removed saved logins from my browser and it solved my issue.
visit https://support.mozilla.org/en-US/questions/962690
https://support.google.com/chrome/answer/95582?hl=en
It is Working in MVC 5, to auto-complete off
#Html.TextBoxFor(model => model.UserName,
new { #placeholder = "UserName", #id = "txtUserName", #autocomplete = "new-user" })
#Html.PasswordFor(model => model.Password,
new {#placeholder = "Password", #id = "txtPassword", #autocomplete = "new-password" })

Editor And ReadOnly Error

I have simple edit form, where you can edit user profile, but you cannot edit username.
So instead this code:
#Html.EditorFor(model => model.username)
I use this line:
#Html.TextBoxFor(model => model.username, new {disabled = "disabled", #readonly = "readonly" })
This works fine, but, I cannot save other fields which are "EditorFor"
e.g. I have column Customers, so one user can have one or more customers, so if I make change in edit, e.g. add new user to customer, and then when I click save, it does not save it. But if I change code again to #Html.EditorFor(model => model.username) then it save it...
Any idea how to fiks this?
The problem is that a read only textbox is not sent back (value is not in POSTed datas).
So if you want to have a readonly textbox AND have the value of username in POSTed datas, you'll have to add a
#Html.HiddenFor(m => m.username)
But... if you just wanna display them, you should just manage that in your controller (don't try to update username... as you don't wanna update username).

Display name instead editor field in MVC4

I have in my edit form displayed: Username, TimeZone, Customer...
I don't whant to be able to edit username, just display his name.
This code I use in View:
<label>Username </label>
<div class="editor-field">
#Html.EditorFor(model => model.username)
</div>
So what to put instead EditorFor, that will display username (just for reading, not for editing).
Why not just use #Html.DisplayFor instead? This will just display the username as a label. Or, if you wish to use #Html.EditorFor or #Html.EditorForModel, you can create a custom editor template for your username property, and in the editor template, just display the content instead of enabling editing.
Also, I would recomment you exclude this property during model binding by using [Bind(Exclude="username")] with your model parameter in your POST action method, to protect from injection attacks. More about this here.
find solution:
#Html.TextBoxFor(model => model.username, new {disabled = "disabled", #readonly = "readonly" })

Resources