I need to use datepicker on an EditorFor field.
My code for the view is:
<div class="editor-label">
#Html.Label("birthDate","birthDate")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.birthDate, new { #class = "datepicker"})
#Html.ValidationMessageFor(model => model.birthDate)
</div>
The script:
<script type="text/javascript">
$(document).ready(
function () {
$('.datepicker').datepicker({
changeMonth: true,
changeYear: true,
minDate: "-99Y",
dateFormat: "dd/mm/yyyy"
});
});
I can't make it work. I have the following error: Microsoft JScript runtime error: Object doesn't support this property or method 'datepicker'.
I have already loaded jQuery before I try to call the function.
#Html.EditorFor(model => model.birthDate, new { #class = "datepicker"})
Will not work, because "EditorFor" will not accept (pass along to the DOM) a Class.
So, you need to use "TextBoxFor" which will accept a Class or better yet, create an EditorTemplate to handle any field that is a DateTime and add the class there. This link details how to make the Template.
Once you have the Class working (can be verified in the source code), the rest is just referencing the jquery code. I use
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
and activating it with the script you already have. Watch that the name '.datepicker' is Exactly the same as the Class.
EditorFor accept a class for me
#Html.EditorFor(model => model.Birthday, new { htmlAttributes = new { #class = "datepicker",#Name="birthday",#PlaceHolder = "mm/dd/yyyy" } })
Html markup
class="datepicker text-box single-line"
The Class is work.
I had a simmilar issue, solved by using the HTML5 functionality, that has support for datetime, in your example I would suggest trying somthing like this:
<div class="editor-label">
#Html.Label("birthDate","birthDate")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.birthDate, new { #class = "datepicker", type="datetime-local"})
#Html.ValidationMessageFor(model => model.birthDate)
</div>
the only thing that I addes is a type ="datetime-local"
Related
I'm trying to bind the Bootstrap 3 Datetimepicker to to my ASP.NET Core model using the MVC tag helper like this:
<div class='input-group date' id='datetimepicker1'>
<input asp-for="Observation.ObservationDateTime" type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
I am hitting a problem initialising the control. The following does not work:
1) in the Razor section scripts like this:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
</script>
}
Doing this initialises the datetimepicker, but without the model value. How do I get it to work but with the model value as the initial value?
Include your date field in the view like this:
#Html.EditorFor(model => model.MyDate, new { htmlAttributes = new { #class = "my-date" } })
And initialize it in your JavaScript like this (I am using jQuery)
$(document).ready(function () {
// get date from MyDate input field
var date = $(".my-date").val();
// use current date as default, if input is empty
if (!date) {
date = new Date();
}
$('.my-date').datetimepicker({
format: 'YYYY/MM/DD',
date: date
});
});
Please note that I am using 'my-date' class as input selector, you may want to select it differently... and obviously you need to include the the bootstrap library...
As a side note, it is best practice to put your script in an external file: why should I avoid inline Scripts
The scenario: I am trying to add a view to Create new users by admin. The app is form authentication. There is a logged in user(admin). When a Password For is added to the view, the view automatically populates the fields with the logged in user.
The controller code:
public ActionResult Create()
{
var userViewModel = new UserViewModel();
return View(userViewModel);
}
The view code:
#model MVC4.Models.UserViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>UserVireModelcs</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
What I suspect is happening here is that the application isn't pre-filling the fields, but the browser is. This is because this form looks exactly like a login prompt. (You can test this by clearing your information from the browser itself so that it doesn't auto-fill any login prompt on this site.)
What I would recommend is to semantically separate the concepts of logging in and creating a user. Basically... rename the fields. A simple view model with some more specific names would help:
public class CreateUserViewModel
{
public string NewUserUsername { get; set; }
public string NewUserPasswords { get; set; }
}
Then use that in your view:
<div class="editor-label">
#Html.LabelFor(model => model. NewUserUsername)
</div>
<div class="editor-field">
#Html.EditorFor(model => model. NewUserUsername)
#Html.ValidationMessageFor(model => model. NewUserUsername)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.NewUserPassword)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.NewUserPassword)
#Html.ValidationMessageFor(model => model.NewUserPassword)
</div>
It's a little more verbose than perhaps one might want it to be (I would agree that simpler is always better), but adding some explicit context to the naming in this case makes it more clear to the browser that this isn't a login form. Use any naming that makes sense for your needs, just make it more descriptive than Username and Password.
i have the following code for view:
#model test1.Models.CustomerVM
#{
ViewBag.Title = "Create";
}
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Customer</legend>
#Html.HiddenFor(model=>model.UserId)
#Html.HiddenFor(model=>model.Id)
<div class="editor-label">
#Html.LabelFor(model => model.User)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User)
#Html.ValidationMessageFor(model => model.User)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ConfirmPassword)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.ConfirmPassword)
#Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.NameTitle)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
#Html.ValidationMessageFor(model => model.NameTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FName)
#Html.ValidationMessageFor(model => model.FName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LName)
#Html.ValidationMessageFor(model => model.LName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Gender, Model.GenderColl)
#Html.ValidationMessageFor(model => model.Gender)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DOB)
#Html.ValidationMessageFor(model => model.DOB)
</div>
#* contacts *#
<div class="editor-label">
#Html.LabelFor(model => model.AddressL1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AddressL1)
#Html.ValidationMessageFor(model => model.AddressL1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddressL2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AddressL2)
#Html.ValidationMessageFor(model => model.AddressL2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Suburb)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Suburb)
#Html.ValidationMessageFor(model => model.Suburb)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Country)
#Html.ValidationMessageFor(model => model.Country)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Phone)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Phone)
#Html.ValidationMessageFor(model => model.Phone)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$('#DOB').datepicker({
appendText: 'mm/dd/yyyy',
showOn: 'both',
buttonText: 'click me',
dateFormat: 'mm/dd/yy',
changeMonth: 'true',
changeYear: 'true',
yearRange: '1900:2016'
});
});
</script>
}
the view works fine displays data as it should be. but when i click Create to save record the following error throws : Object reference not set to an instance of an object This is thrown when it executes the line db.SaveChanges();
Here is the action that does the save. Note: though the view has more field but im not saving all only the ones i have stated in Create() will be saved a.k.a only data in mst_users will be saved
[HttpPost]
public ActionResult Create(CustomerVM custObject)
{
if (ModelState.IsValid)
{
mst_users user = new mst_users
{
uName=custObject.User,
password=custObject.Password,
dtCreated=DateTime.UtcNow,
isLocked=false
};
db.mst_users.Add(user);
db.SaveChanges();
}
}
when i check the receiving data to the method it has all the required data to do the save but funny thing is when it throws the exception the debugger takes the control to the the view and points to the NameTitle field.
Line 44: </div>
Line 45: <div class="editor-field">
Line 46: #Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
Line 47: #Html.ValidationMessageFor(model => model.NameTitle)
Line 48: </div>
here is the table that maps to Entity class mst_users
[uName] varchar
[password] varchar
[dtCreated] datetime
[dtUpdated] datetime
[isLocked] bit
here is the entity class:
here is the video
Here is a null reference error video
As you stated that:
but funny thing is when it throws the exception the debugger takes the control to the the view and points to the NameTitle field.
The problem is not exactly at SaveChanges(), but the exception actually occurs when your action is successfully executed and your same Create view is rendered again. This time, your Model or Model.NameTitleColl is null.
When you make get call to your Create action, you must be populating your CustomerVM method and returning it to view. But after making POST call call to your Create method, if you want to render the same view again, you must populate your CustomerVM again, at the end, and pass it to the view. something like:
[HttpPost]
public ActionResult Create(CustomerVM custObject)
{
if (ModelState.IsValid)
{
mst_users user = new mst_users
{
uName=custObject.User,
password=custObject.Password,
dtCreated=DateTime.UtcNow,
isLocked=false
};
db.mst_users.Add(user);
db.SaveChanges();
}
return View(custObject);
//or return View(new CustomerVM()) just to make you understand
}
UPDATE: (based on video you attached)
You are only populating User, Password and ConfirmPassword field of your CustomerVM model. And you have decorated your Address, Fname and several other properties with *[Required]* attribute. Which means, it MUST not be null when posted, (in order to make model valid). Otherwise, your model state would be invalid. You can clearly see in video, custObject contains null for required values. so exactly as expected, you ModelState.IsValid will give you false in return.
UPDATE: (based on second video you attached)
You are right, your exception occurs at db.SaveChanges() line. The reason for why your debugger takes you to view is following piece of code in your action:
try
{
....
db.SaveChanges();
}
catch()
{
return View(); // <- this line
}
so technically, exception occurs, and the control of your program is moved to your catch block. and you execute return View() in order to handle your exception and when view is rendered, Model.NameTitleColl is null. This throws another exception, which you actually see. whereas, you have skipped the orignal exception.
Reason and Solution:
From your code, I can see, you do not initialize your db object in your action, which throws the orignal exception. Please initialize the db object before you perform any action on it. You can do something like:
db = new YourDbContextNameHere(); //initialize your db object with your Dbcontext class constructor
and then do:
db.mst_users.Add(user);
db.SaveChanges();
it will work fine this way.
This NullPointerException is thrown for db or db.mst_users? In my opinion any one of them is not properly Instantiated.
Based on #Zeeshan answer, I presume your mst_users is being saved to the database the very first time you click the Create button. The problem is likely to be that you are returning same view without passing in the appropriate model that contains the Model.NameTitleColl which is used to populate the dropdown. Hence, the NullExpception.
Update 1
Your model will be invalid because most of your required fields in CustomerVM are null.
For example
the following required field
LName, FName etc are all null. in your video, this values are not provided in the view.
What is a best usag Razor checkbox with postback?
for examle I have a class as follow
public class Person
{
public string Name { get; set; }
public string SurName { get; set; }
public bool hi { get; set; }
}
and a view(with script):
<script type="text/javascript">
$(function () {
$('#hi').change(function () {
$(this).closest("form").submit();
});
});
</script>
#using (Html.BeginForm(FormMethod.Post))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SurName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SurName)
#Html.ValidationMessageFor(model => model.SurName)
</div>
#Html.CheckBoxFor(model => model.hi)
</fieldset>
}
I want postback when I click "hi" checkbox. How can I do it?
a bit jQuery:
$(function(){
$('#hi').change(function () {
$(this).closest("form").submit();
});
});
I haven't tried this out yet. But on the top of my mind, I would add a submit button within the Html.BeginForm(FormMethod.Post) curly braces, and add a style to it to display=none. In other words, it'l be hidden. Then I would add a checkbox event such as onValueChange using jquery (or maybe onClick maybe?, not sure of all of the events by heart.) Within the event block i'd simulate the button click by $('#btnInvisibleButton').Click(); Note that i had trouble executing .Clic() on Safari I think (there's a way around it by adding additional code specific to that browser , so you should test your code on all browsers.
Try this code, just make sure that the submit button is within the form tag:
$('#yourCheckBox').change(function () {
$("#btnInvisibleButton").click();
});
USING : ASP .NET MVC 4
in one of my page i need a textarea with a certain width and height using html helper class. some of my code is given below :
<div class="editor-label">
#Html.LabelFor(model => model.MailSubject)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MailSubject)
#Html.ValidationMessageFor(model => model.MailSubject)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MailBody)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MailBody)
#Html.ValidationMessageFor(model => model.MailBody)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Content)
</div>
<div class="editor-field1">
#Html.EditorFor(model => model.Content)
#Html.ValidationMessageFor(model => model.Content)
</div>
I am wondering how I define the size(width/hide) of the editorfor(model.content)?
I realize this question is over a year old but just in case anyone is looking for the answer, here it is:
Html.TextAreaFor(model => model.Field, new { rows = "", cols = "", style = "width: 90%; height: 50px;" })
You can either apply the styles inline or use the class declaration. This will render the textarea on the page like so:
<textarea class="swiper-no-swiping" name="model.Field" cols="" rows="" style="width: 90%; height: 50px;"></textarea>
I had this problem. I'm a newb, so I'm not really sure, but using the following I was able to adjust the height...
#Html.TextAreaFor(model => model.FullItinerary, 20, 10, null)
I still don't know how to adjust width, my current google mission...
Write a customer helper, or extend the functionality of the TextAreaFor helper.
Here is a resource to help you create a custom helper: http://www.simple-talk.com/dotnet/asp.net/writing-custom-html-helpers-for-asp.net-mvc/