the virtual value in Text Box Asp.net MVC - html

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.

Related

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

MVC Razor Form Set Checkbox to Checked + Lock

I'm building a form and have used the default scaffolding option based on my model in visual studio. What I need is for the checkbox to be checked by default when the view is loaded and disabled. I.E I want to preventing the user from changing the checkbox state.
The view code looks like this:
#model Models.Checkertest
#{
ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Test</h2>
#using (Html.BeginForm("Test", "AccountManagement", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User Creation</h4>
<div class="form-group">
#Html.Label("Enable Bypass", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-4">
<div class="checkbox">
#Html.EditorFor(model => model.box1)
#Html.ValidationMessageFor(model => model.box1, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
}
In your action method in your controller, set the box1 property to true on your model. It would look something like this:
var model = new Checkertest {box1 = true};
return View(model);
To make the checkbox readonly, set the readonly attribute on it, like this:
#Html.EditorFor(model => model.box1, new {#readonly = "readonly"})