Display name instead editor field in MVC4 - asp.net-mvc

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" })

Related

asp.net core mvc application form post with query string parameters

I am building a login form in .net core mvc. Below is my login form
<form class="c-form" asp-controller="Account"
asp-action="Login">
<div class="form-group">
#Html.TextBoxFor(m => m.Username, new { #class = "form-control c-input", placeholder = "Username" })
</div>
<div class="form-group">
#Html.PasswordFor(m => m.Password, new { #class = "form-control c-input", placeholder = "Password" })
</div>
<div class="help-text help-text-error">
#Html.ValidationMessage("UserNamePasswordInvalid")
</div>
<div class="">
<button type="submit" class="btn-c btn-teal login-btn width100">Login</button>
</div>
If a form is posted with incorrect credentials user stays on the page with validation failure messages.
Login page also has return url in query string, when the form is posted query string parameters are lost. What is the correct way of doing form post in .net core.
To keep the query string when the form is submitted write a hidden field in the form containing the query string contents:
#Html.Hidden("returnUrl",#Request.QueryString)
Make sure your controller action that handles the post request has a parameter called returnUrl (or the model that is passed as a parameter has that property) and the model binding will take care of passing it through to the controller. Then in the controller action if the login is successful use that data to redirect accordingly.
I know that it's passed a lot of time, but I found a better solution for this problem.
I added a parameter called QueryString in Model as Dictionary string
in view, in tag form, add
So at this time, the post have the parameters in query string<form asp-all-route-data="#Model.QueryString"
Your controller/PageModel method must contain all parameters that you need to persist. Something like this:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
If the controller and action pair for getting and posting the form is the same, than it is simpler to just delete asp-controller and asp-action attributes from the form opening tag, leaving your like this:
<form class="c-form" method="post">

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).

How do I make validation text appear inside of a textbox?

I am working in an asp.net mvc project and I would like my validation to appear inside of the textbox that it is pertinent to. Currently my code looks like this:
<div class="subStandardOption">
#Html.ValidationMessageFor(model => model.PdsToCreate.Standards.AudioFrequency)
#Html.TextBoxFor(model => model.PdsToCreate.Standards.AudioFrequency)
</div>
The validation only appears the user clicks the checkbox to the left of the text field then tries to submit the form and leaves the textbox is empty, so overwriting the current value is not a concern. When the checkbox is not checked, the textbox is disabled and no validation is necessary.
You can use an HTML5 placeholder to show the required format:
#Html.TextBoxFor(model => model.PdsToCreate.Standards.AudioFrequency, new { placeholder = "e.g. 20 Hz" })

Disable Required Validation Specific Field in the View ASP.NET MVC 4

if someone could give me some hint I would appreciate.
I'm searching for a while, and I even found a post I thought it would solve my problem, but it didn't.
Disable Required validation attribute under certain circumstances
Basically I have a simple User.cs model where I have username, FirstName, LastName and SignupDate
All have the required annotation and I would like to solve this without erasing the Required tag.
After I generate the view, I erase in the view the html code for the SignupDate:
<div class="editor-label">
#Html.LabelFor(model => model.SignupDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SignupDate)
#Html.ValidationMessageFor(model => model.SignupDate)
</div>
When I click submit it does not work.
Also if I do the suggested in the other post
<div class="editor-label">
#Html.LabelFor(model => model.SignupDate)
</div>
<div class="editor-field">
#Html.TexBoxFor(model => model.SignupDate, new { data_val = false })
</div>
If I leave it as blank also does not work..
Any suggestions? Thanks!!
You can disable client validations on the view and remove the errors on the modelstate for those entities you don't want to validate the value.
In my case I wanted to change a Password only if the user typed one. Using Html.HiddenFor was not a good approach due to sends the password to the client every time, and password shouldn't be sent.
What I did was to disable the client validations on the view
#model MyProject.Models.ExistingModelWithRequiredFields
#{
ViewBag.Title = "Edit";
Html.EnableClientValidation(false);
}
That allows me to submit the form even with empty values. Please note that all client validations are ignored, however server validations still run, so you need to clear those you don't need to be executed. In order to do this, go to the action in the controller and remove the errors for each property you need to
public ActionResult Edit(ExistingModelWithRequiredFields updatedModel)
{
var valueToClean = ModelState["RequiredPropertyName"];
valueToClean.Errors.Clear();
if(ModelState.IsValid)
{
...
//Optionally you could run validations again
if(TryValidateModel(updatedModel)
{
...
}
...
}
...
}
I think this should solve it, assuming model.SignupDate holds a value:
<%: Html.HiddenFor(model => model.SignupDate) %>

#Html.EditorFor How to make attribute type="email"

I can do this easily using a TextBoxFor but how do I do it with an EditorFor?
I figured using the DataAnnotation [DataType(DataType.EmailAddress)] but that doesn't do it.
I don't quite understand what the DataType annotation actually does because it doesn't seem to do anything at all at first glance.
You can override the HTML Attributes, to which a browser will fallback to type='text' if they do not support it:
#Html.TextBoxFor(m => m.Email, new { #type = "email" })
it seems to be supported now.
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #type = "email" } })
The EditorFor helper method is somewhat limited out of the box and doesn't yet appear to support the HTML5 type="email" attribute.
Your options right now seem to be either using TextBoxFor or creating a custom template that will allow you to set the input's type attribute. Here's another thread that reviews some of the options for creating your own templates.
The DataAnnotation [DataType(DataType.EmailAddress)] is actually quite useful. It sets the id and name of your form field to email, which you can use with jQuery validation to show the user client-side validation messages. Applying the DataAnnotation to your model class also means that the email property on your model will be automatically validated on the server side. If you enable unobtrusive validation in your app, you get client- and servers-side validation almost for free.
As an addition to jortizromo's answer, you have now at least two options:
Specifying #type in the htmlAttributes parameter for method EditorFor() as in
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #type = "email" } })
Using the EmailAddress annotation attribute from System.ComponentModel.DataAnnotations namespace in the model class definition for the corresponding Email property and a simple call to method EditorFor() (this provides HTML validation data tags which could be a good or bad idea depending on your task) as in
ViewModel
[EmailAddress]
public string Email { get; set; }
Razor View
#Html.EditorFor(model => model.Email)

Resources