DateTime value is not sending back to controller - c#

I cant seem to find the problem here. Really stuck and need help. Im using Html.BeginForm and inside i have editorFor - model.DOB. Used post method but somehow it doesnt send the property back to my controller. Do help. I have other string property fields which is sending fine to the controller. Only date property not sending. TQVM in advance.
---------Edit---------
Just found out that if i use Edge - i need to use dd/MM/yyyy format. Then it will saves fine. If i use MM/dd/yyyy, then it will give null on the controller.
On chrome
using dd/MM/yyyy - gives me 'The field must be a date' error
using MM/dd/yyyy - gives me null.
---------Edit---------
Model
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date of Birth")]
public DateTime? PersonDOB { get; set; }
View
#model Models.CorporationModel
using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<div class="form-group">
#Html.LabelFor(model => model.PersonDOB, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PersonDOB, new { htmlAttributes = new { #class = "form-control", placeholder = "Format: 06/31/1998" } })
#Html.ValidationMessageFor(model => model.PersonDOB, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" name="action:PersonalSave" />
<input type="submit" value="Reprocess" class="btn btn-default" onclick="return confirm('Are you sure?')" name="action:PersonalReprocess" />
</div>
</div>
</div>
}
Controller
[HttpPost]
[MultipleButton(Name = "action", Argument = "PersonalReprocess")]
public ActionResult PersonalReprocess(int id, CorporationModel corporationModel, HttpPostedFileBase postedResultFile, HttpPostedFileBase postedPersonalFile)
{
corporationModel.Verified = "Processing";
return UpdatePersonal(id, corporationModel, postedResultFile, postedPersonalFile);
}
If i remove the
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
Im getting the 'The field must be a date error'. If i switch between month and date manually, then it saves without problem. However, when it pulls from the db, it will start with dd/mm/yyyy and then clicking on save will gives out 'the field must be a date error' again, so need to switch it manually.

Related

DateTime field is null when passing to controller in ASP.NET MVC5

I have in my application a search form using AjaxBeginForm. In the same I have a date field (DateTime), and in which I am using the datePicker bootstrap.
My form looks like this:
#using (Ajax.BeginForm("Index", "Pedido", new AjaxOptions { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "divPedidos" }, new { #class = "form-inline" }))
{
#Html.TextBox("pesquisarRascunhoId", 0, new { style = "display: none" })
<div class="row">
<div class="col-sm-4">
<p>Data emissão</p>
<div class="input-group date col-sm-5">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
#Html.EditorFor(model => model.PedidoFilter.EmissaoInicial, new { htmlAttributes = new { #class = "form-control input-sm datepicker" } })
</div>
a
<div class="input-group date col-sm-5">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
#Html.EditorFor(model => model.PedidoFilter.EmissaoFinal, new { htmlAttributes = new { #class = "form-control input-sm datepicker" } })
</div>
</div>
<div class="btn-search">
<p class="demo-button">
<button type="submit" class="btn btn-success"><i class="fa fa-search"></i><span>Pesquisar</span></button>
</p>
</div>
}
My javaScript for formatting my date in dd / mm / yyyy looks like this:
$(".datepicker").datepicker({
format: "dd/mm/yyyy",
language: "pt-BR",
autoclose: true
});
My entity looks like this:
public class PedidoFilter
{
public DateTime? EmissaoInicial { get; set; }
public DateTime? EmissaoFinal { get; set; }
}
And finally my controller looks like this:
public ActionResult Index(PedidoResult pedidoResult,
{
var pedido = _service.FindAll(pedidoResult.PedidoFilter);
return View(pedido);
}
I define my language culture in my Web.config like this:
<globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" />
All fields of my form arrive in my controller, but my date fields are always null, in the format dd/mm/yyyy, which I define in my datepicker js.
If I enter a date in the mm/dd/yyyy format it is passed to my controller.
My question is:
How can I pass my date field in the dd/mm/yyyy format and get them on my controller without them being null?
I think the date format can be changed with Culture or via the code example below: C# takes the first month of the year after the day. You solve this problem. Use the flatpickr or other datepicker.
<input asp-for="Birthdate" type="datetime" data-name="date-picker" class="form-control" autocomplete="off">
let birthDay = flatpickr(document.getElementById('Birthdate'), {
enableTime: true,
dateFormat: 'd-m-Y',
});
$('#myform').submit((e) => {
$('#Birthdate').val(birthDay.latestSelectedDateObj.toLocaleString());
});

Localization/Validation - MVC C# model only taking my default resource file instead of my other language selected

I am currently trying to get the validation from the backend models to the razor view using resource files. I have 2 languages setup, (en, fr) but even though French is selected, the error message is always in English.
I have tried multiple online tutorial / looking at other people having similar problem but none of the fixes worked for me.
my viewmodel example:
[Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(GlobalRes))]
[Display(Name = "Username", ResourceType = typeof(GlobalRes))]
public string Username { get; set; }
[Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(GlobalRes))]
[DataType(DataType.Password)]
[Display(Name = "Password", ResourceType = typeof(GlobalRes))]
public string Password { get; set; }
Razor view:
<div class="form-group">
#Html.LabelFor(m => m.Username, new { #class = "col-md-12" })
<div class="col-md-12">
#Html.TextBoxFor(m => m.Username, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Username, "", new { #class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-12" })
<div class="col-md-12">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
</div>
Inspecting the html in your browser after changing the language and submitting the form.
<input class="input-validation-error form-control" data-val="true" data-val-required="Ce champ est requis." id="Username" name="Username" type="text" value="">
<span class="field-validation-error text-danger" data-valmsg-for="Username" data-valmsg-replace="true">This field is required.</span>
<input class="input-validation-error form-control" data-val="true" data-val-required="Ce champ est requis." id="Password" name="Password" type="password">
<span class="field-validation-error text-danger" data-valmsg-for="Password" data-valmsg-replace="true">This field is required.</span>
What the expected results should be is, based on the language selected, the error message should be in french. If you inspect the input box, you can see the correct value being added in french. When submitting the form, you actually only get the english value instead of the expected one.
Thank you in advance!
I had this problem also but I find a simple way, I controller add this code.
if (ModelState.IsValid)
{
}
else
{
ModelState.Clear();
TryValidateModel(Model);
}
I was having the exactly same issue. For me putting the resource files in App_GlobalResources folder solved my problem!
If that folder does not exist already you can create it.
I am using localization on Asp.Net MVC application.

Implementing Validation in MVC

Trying to validate my Phone Number so no one can input random letters inside the input box. I do have the unobtrusive and validate scripts. So far I have tried a few things inside my Model,
[RegularExpression(#"^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$", ErrorMessage = "Not a valid Phone number")]
[Display(Name = "Phone")]
public string SMSPhoneNumber;
or
[DataType(DataType.PhoneNumber)]
public string SMSPhoneNumber;
This is my View
<form role="form" action="#">
#Html.AntiForgeryToken()
<div class="form-group">
<label class="control-label"><b>Phone Number</b></label>
#Html.TextBoxFor(model => model.SMSPhoneNumber, new {#class = "form-control", #placeholder = "Enter Phone Number", #id = "phoneNumber", Name = "phoneNumber", data_val_required = "Please enter a phone number"})
#Html.ValidationMessageFor(model => model.SMSPhoneNumber, null, new { #class = "text-danger" })
</div>
<button type="button" data-dismiss="modal" class="btn dark btn-outline"> Cancel</button>
<button type="button" data-toggle="modal" id="" class="btn green" onclick="javascript: updateDatabase();">Submit</button>
</form>
This is my controller
[HttpPost]
public ActionResult UpdatePhoneNumber(string phoneNumber)
{
if (ModelState.IsValid)
{
return View();
}
}
The validation is still not working, what could be the issue?
Thanks
The reason your do not get client side validation is that you have changed the name attribute by using new { Name = "phoneNumber" } and you have not created a validation message placeholder for phoneNumber (just one for SMSPhoneNumber).
Under no circumstances should you ever change the name attribute. Nor should you be adding data-val-* attributes (and its not clear why your changing the id attribute). The HtmlHelper methods will always generate the correct html for model binding and validation when used correctly.
The reason you do not get any server side validation is that your not binding to your model, just to a string.
Change the view code to
#Html.TextBoxFor(m => m.SMSPhoneNumber, new { #class = "form-control", placeholder = "Enter Phone Number" })
#Html.ValidationMessageFor(m => m.SMSPhoneNumber, null, new { #class = "text-danger" })
and change the POST method to receive your model (assuming its say public class Company), then
[HttpPost]
public ActionResult UpdatePhoneNumber(Company model)

how to save text with multilines in textarea in asp mvc

Here's the view which I'm using to enter the multiline article
I wish that you can also told me how to save the text properties such as bold italic too because it makes me very confused.
#model WEBSITI.Models.article
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm( "Create", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.bodyofarticle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.bodyofarticle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.bodyofarticle, "", new { #class = "text-danger" })
</div>
<input type="file" id="file" name="file" />
</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>
</div>
}
When a form is submitted, the asp.met mvc framework will inspect the request body to see whether it has any potentially dangerous content as HTML markup(Think about script injection). If it detects any dangerous content,the Request Validation module will throw an error. This is by design
To explicitly allow the form posting with Html tags inside the property value, you may decorate your specific property with the AllowHtml attribute
public partial class article
{
[AllowHtml]
public string bodyofarticle { set; get; }
//other properties here
}
This will tell the framework to exclude this property from the above request validation.
I suggest you follow PascalCasing while writing C# code ( Ex : Article instead of article)

The value is invalid yet should it is a valid input value

I'm creating a webpage using MVC 5, Visual Studio, C#.
In my view I have a remark page which the user is allowed to make a remark in a text box and click "save" to save the remark in a database. However, it is saying that the value of the remark is invalid when it shouldn't be.
The error is
The value 'Testing Remark' is invalid
yet it should be valid
In my model, I have a class called Recall, which has a
public string Remark {get; set;}
In the view I have
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(model=>model.Remark, htmlAttributes: new {#class ="control-label col-md-2"})
<div class="col-md-10">
#Html.TextAreaFor(model => model.Remark, 5, 50, new { #class = "text-danger"})
#Html.validationMessageFor(model => model.Remark, "", new { #class = "text-danger"})
</div>
</div>
<div class="form-group">
<input type="submit" value="save" class="btn btn-default" />
</div>
}
In the controller
....
not putting the controller code here since it should have nothing to do with the error I'm getting.
You should use data type MultilineText if you are using a TextArea:
[DataType(DataType.MultilineText)]
public string Remark { get; set; }
Or just change the TextAreaFor to a TextBoxFor if you don't need multi line text:
#Html.TextBoxFor(model => model.Remark, new { #class = "text-danger"})

Categories

Resources