I am unable to find a solution for this as I think this is a bug, or maybe I am not seeing something I should have.
I am passing a model from controlled to view as strongly typed data. However, only one parameter is bugged, it clears it's data after post-back.
When I click Search..
You can see here, the date from Closed Time is still there, but the text from Cut Off time has gone. The date you see at the end is the value of #Model.CutOffTimeFrom - #Model.CutOffTimeTo just to see if the data was cleared or deleted, but it's not, it's just the display on the EditorFor was removed.
I also tried this one, using <input> tag but it's still the same output.
Below is my model:
[AssertThat("CutOffTimeFrom <= CutOffTimeTo", ErrorMessage = "Date To should be greater than Date From")]
[RequiredIf("CutOffTimeFrom != null", ErrorMessage = "Date From is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? CutOffTimeFrom { get; set; }
[RequiredIf("CutOffTimeTo != null", ErrorMessage = "Cut Off Time From is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? CutOffTimeTo { get; set; }
and here is the view:
<div>
#*<input type="date" name="CutOffTimeFrom" value="#Model.CutOffTimeFrom" class="form-control input-sm" />-<input type="date" name="CutOffTimeTo" value="#Model.CutOffTimeTo" class="form-control input-sm" />*#
#Html.EditorFor(m => m.CutOffTimeFrom, new { htmlAttributes = new { #class = "form-control input-sm" } }) - #Html.EditorFor(m => m.CutOffTimeTo, new { htmlAttributes = new { #class = "form-control input-sm" } })
#Html.ValidationMessageFor(model => model.CutOffTimeFrom, "", new { #class = "text-danger" })
#Html.ValidationMessageFor(model => model.CutOffTimeTo, "", new { #class = "text-danger" })
</div>
All other fields works just fine. Only Cut Off time is being cleared, although it satisfies the search criteria, value is still passed on the model, but it's just not displayed on the view.
Anyone encountered this issue?
Can we see the Controller handling this, because it might happen that its not model binding
I thoroughly checked the differences of each element, property, parameter and saw one difference, the date format. Saw the bug upon checking inspect element of each EditorFor and saw they were different dates, 2019/02/08 and 02/08/2019, where the latter is wrong.
Changed it from:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
To:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Probably the [DataType(DataType.Date)] is unable to render 02/08/2019 that's why it doesn't repopulate the form.
Related
This is part of a .NET MVC project.
I have a DropDownList that is populated by an array of strings from my model. The actual list functions fine and populates correctly, but when an item is selected, there is no value passed. The value should just be equal to the text being selected from the dropdownlist.
I can see that it likely isn't assigned anywhere, but I'm relatively inexperienced with MVC/HTML projects.
<div class="form-group">
#Html.LabelFor(model => model.Cores, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Cores", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Cores, "", new { #class = "text-danger" })
</div>
</div>
The code I'm using is modified from a larger project that I've (apparently) taken over, so I'm learning as I go with this.
EDIT:
This is how the list of cores is initialized and passed to the view page.
var cores = db.Cores.ToList();
var coreName = new List<string>();
foreach (Core core in cores)
{
coreName.Add(core.Name);
}
ViewBag.Cores = new SelectList(coreName);
return View();
You're just creating a dropdown which is not binded to your model. You should use Html.DropDownListFor, not Html.DropDownList.
public class MyModel {
public string Core { get; set; }
}
In your view file,
#Html.DropDownListFor(n => n.Core, (SelectList)ViewBag.Cores, htmlAttributes: new { #class = "form-control" })
And post action in your controller
[HttpPost]
public ActionResult Report(MyModel model)
{
//model.Core is selected core.
}
UPDATE:
If you don't have a Model,
In your view file,
#Html.DropDownList("Core", (SelectList)ViewBag.Cores, htmlAttributes: new { #class = "form-control" })
And post action in your controller
[HttpPost]
public ActionResult Report(string Core)
{
//Core is the selected one.
}
I have an ASP.NET MVC 5 project. I added internationalization and resources files, and now want to use some of those resources in the labels for the login for and registration form.
My question is how do I do this? If I just remove the razor code and put in the resource code, the layout is off.
Here is a code fragment:
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
Now I want to change the #Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })part with #Resources.Resources.RegisterIntro while keeping the layout as it is.
Is this possible?
There are two ways 1"direct annotations" 2"Annotatinos with a resource"
Direct annotations
[Display(Name = "My Field")]
public string MyField { get; set; }
Annotatinos with a resource
[Display(Name = "My_Field",ResourceType = typeof(Resource))]
public string MyField { get; set; }
Second way will require to add a value in resource file Resource.resx.
Use which suits your purpose.
I have two inputs of type file, one in a partial view, and another in main page
In partial view
<input type="file" name="image" id="image" onchange="readURL(this)"/>
In main page
<input type="file" name="userProfilePic" id="userProfilePic" style="display:none" />
What I want is that when a user changes image/file on the visible file upload, the image/file should be updated on main/other input too. Here's my code.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
// window['profilePic'] = input.files[0];
$('#userProfilePic').get(0).files[0] = input.files[0];
return false;
}
The Error
The error is quite weird, when I open my console, and check for files, it shows up sometime, and a moment later it don't.
In my console window
$('#userProfilePic').get(0).files[0]
File (file object details)
....
(after a second)
$('#userProfilePic').get(0).files[0]
undefined
And it isn't happening the first time only. Say sometimes, it shows the values for 5-6 times, then 7th time it won't...
$('#userProfilePic').get(0).files[0]
File (file object details)
....
(after a second)
$('#userProfilePic').get(0).files[0]
File (file object details)
....
(after a second)
$('#userProfilePic').get(0).files[0]
File (file object details)
....
(after a second)
$('#userProfilePic').get(0).files[0]
undefined
That's all the code I have, there is no other code. Now, as you can see in the code, I also set window[profilePic] to the file object. But if I check that in console window, it always shows no matter what? How is this happening?
The problem
I need to submit the form, but when I do, the image (the input file) is being sent as null, but sometimes as a valid file. As I explained earlier, when I check the value in console, it shows for first time, or some random number of times, then all of a sudden it is gone, while the variable that I set on window (window[profilePic]) always have that file object.
In case someone is wondering, the original/visible file input where user actually selects the file always has the value.
You cant do this for security reasons , all files uploaded via input type="file" have to be done manually by the user.
However as long as the user will upload an image anyway , you should do all the process you want in your server side script.
for further info , please refer to this post here :
How to set a value to a file input in HTML?
Why you try to use two inputfile for the same file?
if you try to make a form in a PartialView with a inputfile and extra data? I answered a very similar question here:
File upload in MVC when used in bootstrap modal returns null
1) make a model for used in the form with all elements for the form,
2) declare the model in the first line in the partial view
3) pass as parameter the model to the post function.
4) you use a Partial view, well is possible use this view in differents pages, you need specify the control to treatement the form.
An Example in code:
Model:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class PartialFormModel
{
[Required]
[StringLength(200)]
public string FileName { get; set; }
[StringLength(200)]
public string Title { get; set; }
[StringLength(1000)]
public string Description { get; set; }
public int? Order { get; set; }
[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }
}
PartialVIEW:
#model YOURSPACENAME.Models.PartialFormModel
#using (Html.BeginForm("YourActionName", "YourControllerName", FormMethod.Post, new { #class = "form-horizontal", #role = "form", #enctype="multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(model => model.FileName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FileName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FileName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageFile, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.ImageFile, new { #class = "form-control", type = "file" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
CONTROLLER
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult YourActionName(PartialFormModel obj)
{
if (ModelState.IsValid)
{
//your options
}
return PartialView("_EditSlider");
}
Considering that:
For security reasons you can't set value of input type="file"
programmatically.
Changing the type of an <input> throws a security error in some
browsers (old IE and Firefox versions).
I don't know actually what you want. But I exhort you to create a new input element, set its type to the one you want, say file, and set its properties according to your need. like this:
<script>
function createInputType(_type, _value, _name, _id, _class) {
var newObject = document.createElement('input');
newObject.type = _type;
newObject.value = _value;
newObject.name = _name;
newObject.id = _id;
newObject.className = _class;
return newObject;
}
</script>
I am building an MVC4 app and in my model I have these fields:
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime mDateCreated { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? mDateModified { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? mDateLastDisplayed { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime mStartDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? mEndDate { get; set; }
I am trying to set datepickers in a view. Here's what I have done so far:
<div class="float-left">
<p>Date Created:</p>
<p>Date of last modification:</p>
<p>Date Last Displayed:</p>
<p>Date of promotion's start:</p>
<p>Date of promotion's end:</p>
</div>
<div class="float-right">
<p>
#Html.TextBoxFor(_item => _item.mCardOfTheDay.mDateCreated, new
{
#value = Model.mCardOfTheDay.mDateCreated,
#selectedDate = Model.mCardOfTheDay.mDateCreated,
#class = "datePick",
#type = "date",
#id = "dateCreated"
})
</p>
<p>
#(Model.mCardOfTheDay.mDateModified != null ? Html.DisplayFor(_item => _item.mCardOfTheDay.mDateModified) : Html.Label(ValueDomain.FIELD_UNAVAILABLE))
</p>
<p>#(Model.mCardOfTheDay.mDateLastDisplayed != null ? Html.DisplayFor(_item => _item.mCardOfTheDay.mDateLastDisplayed) : Html.Label(ValueDomain.FIELD_UNAVAILABLE))</p>
<p>
#*#Html.EditorFor(_item => _item.mCardOfTheDay.mStartDate, new { #class = "datePick", #type="date" })*#
#*#Html.TextBoxFor(_item => _item.mCardOfTheDay.mStartDate, new {#id = "dateStart"})*#
#* #Html.TextBoxFor(_item => _item.mCardOfTheDay.mStartDate, new
{
#value = (DateTime?) Model.mCardOfTheDay.mStartDate,
#selectedDate = (DateTime?) Model.mCardOfTheDay.mStartDate,
#class = "datePick",
#type = "date",
#id = "dateStart"
})*#
</p>
<p>
#Html.TextBoxFor(_item => _item.mCardOfTheDay.mEndDate, new
{
#value = Model.mCardOfTheDay.mEndDate,
#selectedDate = Model.mCardOfTheDay.mEndDate,
#class = "datePick",
#type = "date",
#id = "dateEnd"
})
</p>
</div>
<div class="clear"></div>
And CSS to show what I'm doing with the classes:
$('.datePick').datepicker({
dateFormat: "dd/ww/yy",
});
$('.datePick').each(function () {
var a = $(this).datepicker({
dateFormat: "dd/ww/yy",
defaultDate: new Date($(this).val())
});
});
This shows the various problems I have. First:
Using Html.TexborFor helpers with #value, #selectedDate and so on does displays a datepicker, but this datepicker's default shown value is aaaa-mm-dd instead of the value binded to the model and when I pass the model to the controller none of the data is kept (meaning that the mEndDate is always null);
Trying only to set a datepicker ends up with the same results;
Here's a sample of Html code behind to show you the "results" I have: <input class="input-validation-error datePick" data-val="true" data-val-date="The field mDateCreated must be a date." data-val-required="The mDateCreated field is required." id="dateCreated" name="mCardOfTheDay.mDateCreated" selectedDate="11/21/2013 00:00:00" type="date" value="" />
And if I use the EditorFor, all I have is a date in string format, no datepicker.
What I want is a datepicker with the proper date selected that passed the selected date to the controller method in post. Can anyone help me figure out why this does not work?
You shouldn't be overriding the value of the date input with the same date in a different format, there is no reason to and it will only cause headaches. From my experience you're better off leaving it as is.
#Html.TextBoxFor(_item => _item.mCardOfTheDay.mDateCreated, new
{
#selectedDate = Model.mCardOfTheDay.mDateCreated,
#class = "datePick",
#type = "date",
#id = "dateCreated"
})
What you need to do however is configure the datepicker properly so that it knows how to interpret the date coming from your database. If you want to show a different format to the user than the one posted back to the server, you can make use of the altField (source) and altFormat (source) option.
That will allow you to use dateFormat to display the date in whichever format you like in the input to the user, while keeping the posted value in the right format.
You won't need this anymore :
$('.datePick').each(function () {
var a = $(this).datepicker({
dateFormat: "dd/ww/yy",
defaultDate: new Date($(this).val())
});
});
You'll also need to get rid of ApplyFormatInEditMode = true on your model property attributes. Let the framework handle dates based on current culture, don't try working against it by applying formats all over the place.
Just leave the textbox value be whatever your database sends, and use the datapicker's functionality to do what you need on the client side.
The only time I would advise overriding the value is if you're worried about the input showing the time part when you only want the date. In that case, you should do it like so :
#Html.TextBoxFor(_item => _item.mCardOfTheDay.mDateCreated, new
{
#selectedDate = Model.mCardOfTheDay.mDateCreated,
#class = "datePick",
#type = "date",
#id = "dateCreated",
#Value = Model.mCardOfTheDay.mDateCreated.ToString("mm/d/yyyy")
})
Notice #Value with a capital v, that is actually important and not a typo. You then pass a date format to the ToString method, but it needs to be the same format as your database.
Edit:
I went ahead and built a small test-case to try and replicate your issue. Here's what I have :
Controller :
public ActionResult Test()
{
return View(new TestViewModel()
{
DateCreated = DateTime.Now.AddDays(10)
});
}
[HttpPost]
public ActionResult Test(TestViewModel model)
{
return RedirectToAction("Test");
}
ViewModel :
public class TestViewModel
{
public DateTime DateCreated { get; set; }
}
View :
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.DateCreated, new {
#type = "date",
#Value = Model.DateCreated.ToString("d")
})
<input type="submit">
}
// This is the rendered input
<input Value="12/1/2013" data-val="true" data-val-date="The field DateCreated must be a date." id="DateCreated" name="DateCreated" type="date" value="12/1/2013 4:03:19 PM" />
JS:
$('input[type="date"]').datepicker();
This all works as expected; datepicker has the date in the input's value selected by default, value of model.DateCreated is set to a DateTime object on post. Notice I haven't messed with formats anywhere but in the display value where I replaced the full date with the standard short date pattern.
Can you try simplifying your code to match what I have and let me know what happens?
Well, after so many years you would definitely have sorted out this issue but still wanted to answer for all those who are new to this problem:
The datepicker should take the format YYYY-MM-DD as its value. Single digit days and months should be padded with a 0. January is 01. You can simply modify your date format as
#Value = Model.DateCreated.ToString("yyyy-MM-dd")
USING ASP .Net MVC 4 , Razor View
I have a CheckBoxFor:
<div class="editor-checkbox-field">
#Html.CheckBoxFor(model => model.Is2ndMailBody, new { #name = "secMailBody", #id = "secMailBody", #class = "secMailBody", #onclick = "disable(this.form.secMailBody)", #value = "Create Table", #text = "Create Table" })
</div>
But the CheckBox itself is showing. How can i show a text what the CheckBox for?
my model has :
public bool IsChecked { get; set; }
javascript is working fine and css also. I just want to know how i can show a text for this checkbox?
EDIT 1 :
I want the text Create Second Mail Body in the right side of the check box.
Answer 1: Just put the string right after the CheckBox like below.
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.Is2ndMailBody) Create Second Mail Body
</label>
</div>
Answer 2: In Model,
[Display(Name = "Create Second Mail Body")]
public bool Is2ndMailBody{ get; set; }
In View
<div>
#Html.CheckBoxFor(m => m.IsChecked)
#Html.LabelFor(m => m.Is2ndMailBody)
</div>
First add filter to your model that called DisplayAttribute
[Display(Name = "Some Text")]
public bool IsChecked { get; set; }
And you can use Label for model
#Html.LabelFor(model => model.Is2ndMailBody)
You can use
#Html.DisplayNameFor
instead of
#Html.LabelFor
in Alizra's answer. This way, .label css style won't be applied to your text.
If you are using bootstrap you can do this
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.Is2ndMailBody) Create Second Mail Body
#Html.ValidationMessageFor(m => m.Is2ndMailBody)
</label>
</div>
example from: http://getbootstrap.com/css/
In your model class use Data Annotations to give a display name to the property
You need to have this using statement on top of the model class
using System.ComponentModel.DataAnnotations;
Then set the Display Name attribute
[Display(Name = "Create second mail body")]
public bool IsChecked { get; set; }
After that in your view use wrap the checkbox with the following div tag. You will need to have bootstrap CSS referenced in the view if it's not
<div class="checkbox">
#Html.CheckBoxFor(m => m.Is2ndMailBody, new { htmlAttributes = new { #class = "form-control" } })
#Html.LabelFor(m => m.Is2ndMailBody, new { #class = "control-label" })
</div>
Hope this will help
You can try this:
<div class="editor-checkbox-field">
<label> Create Second Mail Body #Html.CheckBoxFor(model => model.Is2ndMailBody, new { #name = "secMailBody", #id = "secMailBody", #class = "secMailBody", #onclick = "disable(this.form.secMailBody)", #value = "Create Table", #text = "Create Table" }) </label>
</div>
That is:
<label> Your text #HTML.checkBoxFor() </label>