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...
Related
I have a text box in the Crete view in the asp.net mvc , and i want to put the virtual value 0 in this text box so when i save it will save in the database as 0 how i can do that?
enter image description here
<div class="form-group">
#Html.LabelFor(model => model.Credit, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Credit, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Credit, "", new { #class = "text-danger" })
</div>
</div>
this is the controller:
// GET: DailyTransactions/Create
public ActionResult Create()
{
var Customers = _context.Customers.ToList();
List<SelectListItem> list = new List<SelectListItem>();
foreach (var item in Customers)
{
list.Add(new SelectListItem { Text = item.Customer_Name, Value = item.Customer_Id.ToString() });
ViewBag.Customers = list;
}
return View();
}
To illustrate the idea i have in my project value in database name is credit so i want put this value as 0 i mean the virtual value 0 , so when i add some number to this credit the 0 will be increase .
so i Crete the text box and i want to put the virtual value 0 in this text box.
i hope you understand what i want.
thank you
If you want to "suggest" a value without setting it, you use placeholder:
<input id="Text1" type="text" placeholder="0"/>
If you want to set a default value, then you set that value like this:
<input id="Text1" type="text" value="0" />
If you want to bind a value to your model, you use:
// your imports / declarations
#model myModel;
#using (Html.BeginForm())
{
// other html / razor code
#Html.EditorFor(myModel => myModel.myNumber);
}
This should help, just copy and paste over your EditorFor
#Html.TextBoxFor(model => model.Credit, htmlAttributes: new { #class = "form-control" , #Value = "0", #placeholder = "0",#min="0" })
As you can see I added the html attribute in the MVC html helper and added a min so the values below 0 will not be accepted.
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;" } })
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"
}
})
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"} })
I'm using umbraco and letting it handle allowing my users to log in. I tried creating my own log in MVC but there is a lot of logic already built upon the old way. And I don't want to spend the time having to re-build it.
There for, I was wondering if there was anyway I could add in a hidden field that would allow the user to be redirected to my home page when the log in using the following form code:
#using (Html.BeginUmbracoForm<UmbLoginController>("HandleLogin"))
{
<legend>Login</legend>
#Html.ValidationSummary("loginModel", true)
#Html.TextBoxFor(m => loginModel.Username, new { #class = "form-control", #placeholder = "Username" })
#Html.ValidationMessageFor(m => loginModel.Username, "", new { #class = "alert-danger", #role = "alert" })
<br />
#Html.PasswordFor(m => loginModel.Password, new { #class = "form-control", #placeholder = "Password" })
#Html.ValidationMessageFor(m => loginModel.Password, "", new { #class = "alert-danger", #role = "alert" })
<br />
<button class="btn btn-default">Login</button>
}
You should be able to set the loginModel.RedirectUrl at the point where you're creating it, and then add the following to your form:
#Html.HiddenFor(m => loginModel.RedirectUrl)