How do I add other attributes to htmlAttributes? - html

The code below works, but when I try to add another attribute to htmlAttributes, it shows an error that I cannot do this.
#Html.EditorFor(model => model, new { htmlAttributes = new { #class = "form
control" } });

You are putting the next attribute outside of the htmlAttributes object by the looks of it. Instead, you want this:
#Html.EditorFor(model => model, new { htmlAttributes = new { #class = "form control", style = "background: blue" }})

You need to do something like following:
#Html.EditorFor(model => model, htmlAttributes: new { #class = "form control",
id="id"
}
})

Related

Textbox width in razor

how to adjust textbox width in razor code? My code below does not work:
#Html.EditorFor(model => model.PDFLink, new { htmlAttributes = new {#class = "form-control",style="width:300px" } })
Thanks.
You can create a class with the Width you want and use that class for all text box you want. Something like below.
.setWith {
max-width: 350px;
}
#Html.EditorFor(model => model.PDFLink, "", new { #class = "form-control setWith", placeholder = "If You want Any.." })
I did something like this and it works.
#Html.EditorFor(model => model.PDFLink, new { htmlAttributes = new { #class = "form-control",#style="100% !important; min-width:600px;" } })

Auto-resize #Html.EditorFor (ASP.NET MVC)

I have #Html.EditorFor , here is code. I need it to resize on height when I enter text.
#Html.EditorFor(model => model.question, new { htmlAttributes = new { #class = "form-control", placeholder = "Вопрос" } })
How I can do this?

How to put a placeholder for a dropdown list

I cannot manage to put a placeholder titled "Please Select", so I simply put it as an item in my drop-down, but now "Please select" can be selected, which is a bit of a nuisance. Is there a way to have a place holder for the drop-down list below.
<div class="form-group">
#Html.LabelFor(model => model.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Type, new List<SelectListItem>
{ new SelectListItem{Text="Please select type"},
new SelectListItem{Text="Book"},
new SelectListItem{Text="Book chapter"},
new SelectListItem{Text="Journal article"},
new SelectListItem{Text="Conference"}}, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
Overloads 4, 5 & 6 of the DropDownListFor helper all contain a parameter optionLabel, which can be used for your purposes.

Autofocus on EditorFor

I would like to autofocus on an editorfor in my application, but I can't seem to do that. I have successfully used autofocus on a textbox, but I would like to use an editorfor to keep my application's look universal.
Any solutions to this would be much appreciated, thank you.
My attempt:
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" }, autofocus = "" })
This s because you are using EditorFor instead of something specific like TextBoxFor.
#Html.TextBoxFor(model => model.Name, new { htmlAttributes = new {
#class = "form-control" }, autofocus="autofocus"})
Or you can do that using jQuery:
<div class="editor-field focus">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
$(function() {
$('.focus :input').focus();
});
Update:
As you know TextBoxFor always creates a textbox with type input, But EditorFor is a little bit smart, it renders markup based on the datatype of the property.
Using .Net Framework 4.5 and MVC 5, this works for me:
#Html.EditorFor(model => model.Description, new {
htmlAttributes = new {
#class = "form-control",
autofocus = true
}
})
You put the autofocus attribute in the wrong spot.
#Html.EditorFor(model => model.Description,
new { htmlAttributes = new { #class = "form-control" }, autofocus = "" })
Try this instead:
#Html.EditorFor(model => model.Description,
new { htmlAttributes = new { #class = "form-control", autofocus = "" } })
I've been following this thread and I may have stumbled on an answer to your question about autofocus on EditorFor - this is all Asp.Net 4.5 and MVC 5, not that it matters.
In the Scripts folder I have a jQuery script file:
$(function(){
$('.someclassname').focus();
});
I add the script name to the BundleConfig and render it in the view.
In the view I add the classname to the EditorFor <div class="col-md-10" someclassname">
I then add the type="text" autofocus="autofocus" to the EditorFor's #class. So, new{#class="form-control", type="text", autofocus="autofocus"
That's pretty much it, when the DOM loads the .someclassname field gets the cursor focus...
PS. In fact if you just do (3) it works also...

How can I make my EditorFor disabled?

I have an MVC Razor Create view and my model contains one or more fields that need to be auto-filled by the system, such as "Timestamp" and "Username". Because these fields are required, they need to be in the form.
Here is an example of what the default code looks like when you allow Visual Studio to scaffold your views from a controller.
<div class="form-group">
#Html.LabelFor(model => model.RoseUserName,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RoseUserName,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RoseUserName, "",
new { #class = "text-danger" })
</div>
</div>
This what the code looks like when rendered. It's functional, but the first and third fields are fully editable when it shouldn't be. So the question is how we can have EditorFor fields that feed the correct data into the model when the form is submitted but that the user can't change?
Further Explanation
While there are some reasons you might want to keep those fields hidden from view, there are also valid reasons you would want these fields to be seen by the user, such as in a company intranet with users who expect to see that information. While a datestamp could be autogenerated by SQL Server with a getdate() default value, capturing the user's identity under Windows Authentication would need to be done from from the MVC side. The identification of the user is part of the model.
An important database features is the ability to have computed properties. If you're mapping your code first classes to tables that contain computed properties, you don't want Entity Framework to try to update those columns. But you do want EF to return those values from the database after you've inserted or updated data. You can use the DatabaseGenerated annotation to flag those properties in your class along with the Computed enum. Other enums are None and Identity.
[DatabaseGenerated(DatabaseGenerationOption.Computed)]
public DateTime DateCreated { get; set; }
Now just have your database generate the time stamp when the record is created. You can also set DataAnnotation to read only like so
[DatabaseGenerated(DatabaseGenerationOption.Computed)]
[Editable(false)]
public DateTime DateCreated { get; set; }
Hope this helps
Update
// Private
private DateTime _createdOn = DateTime.Now;
// Public property
[Display(Name = "Created On")]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime CreatedOn
{
get
{
return (_createdOn == DateTime.MinValue) ? DateTime.Now : _createdOn;
}
set { _createdOn = value; }
}
Or in the View.
#Html.HiddenFor(model => model.CommentTime, new { #Value=System.DateTime.Now })
Or in the controller.
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
If done in the controller and/or model you can use the html attribute of readonly like so.
You could use a custom editor template:
public class MyViewModel
{
[UIHint("MyHiddenDate")]
public DateTime Date { get; set; }
}
and then define ~/Views/Shared/EditorTemplates/MyHiddenDate.cshtml:
#model DateTime
#Html.Hidden("", Model.ToString("dd/MM/yyyy"))
and finally in your view use the EditorFor helper:
#model MyViewModel
#Html.EditorFor(x => x.Date)
This will render the custom editor template for the Date property of the view model and consequently render the hidden field with a value using the desired format.
UPDATE
The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:
<div class="editor-field">
#Html.TextBoxFor(model => model.DateCreated , new
{ disabled = "disabled", #readonly = "readonly" })
</div>
You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:
public class MyModel
{
[UIHint("DateCreated ")]
public string DateCreated { ;get; set; }
}
Then, in your Views/Shared/EditorTemplates folder, create a file DateCreated .cshtml. In that file, put this:
#model string
#Html.TextBoxFor(m => m, new { #readonly = "readonly" })
When I posted this answer, it was based on what I was able to find so far. I have learned that this is a case of "Beware what you wish for." The other answers provided point out correctly that following the approach shown below is not a good practice and has at least one false premise, as explained in the conversation thread.
This is useful only as an explanation of what NOT to do. The answer I accepted shows the approach I adopted.
The answer is amazingly simple and elegant. Tt just takes an extra phrase: #readonly="readonly".
In better context, the original example was:
<div class="form-group">
#Html.LabelFor(model => model.RoseUserName,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RoseUserName,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RoseUserName, "",
new { #class = "text-danger" })
</div>
All you do is add#readonly="readonly"to the EditorFor htmlAttributes, like this:
#Html.EditorFor(model => model.RoseUserName,
new { htmlAttributes = new { #class = "form-control", #readonly="readonly" } })
Problem solved.
<div class="form-group">
#Html.LabelFor(model => model.RoseUserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RoseUserName, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly"} })
#Html.ValidationMessageFor(model => model.RoseUserName, "", new { #class = "text-danger" })
</div>
</div>
Add disabled = "disabled", #readonly = "readonly" along with #class = "form-control", so you have:
#Html.EditorFor(model => model.RoseUserName, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly"} })