01/01/0001 when passing birth date to control - validation

I want to save a register form and must save birth date in another format.
In model I have:
public DateTime BirthDate { get; set; }
In the view:
#model Univer.Model.KarApplicant
#{
ViewData["Title"] = "";
}
<div class="container MainMiddle" style="padding-top:50px;">
<hr />
<div class="row container-fluid">
<div class="col-md-10">
<form asp-action="Register">
<div asp-validation-summary="ModelOnly" class="text-danger">
</div>
<div class="form-row">
....
<div class="form-group col-md-4">
<label asp-for="BirthDate" class="control-label"></label>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-calendar-alt"></i></div>
</div>
<input asp-for="BirthDate" class="form-control example1" data-val="false" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
</div>
</div>
</div>
....
<div class="form-row">
</div>
<div class="form-group float-left">
<input type="submit" value="next" class="btn btn-lg btn-primary btn-block" />
</div>
</div>
</form>
</div>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/lib/persian-date/persian-date.js"></script>
<script src="~/lib/persian-datepicker/js/persian-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".example1").pDatepicker();
});
</script>
}
When I click on Submit button and send data to action of controller, with breakpoint check form value that pass to controller, birth dates value that are passed to controller is 01/01/0001 but I have value in persian mode in input in view.
My question is: why when set value with javascript in input and send to controller the value doesn't get sent?
UPDATE: after the comment i Added this code
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("fa-IR");
}); .....
}
and
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{....
app.UseRequestLocalization();
app.UseMvc()....
}

Related

My create.cshtml view page not opening ASP.NET Core 6 MVC application in Visual Studio 2022

I am creating an ASP.NET Core 6 MVC application, the application runs successfully but whenever I want to add an actor (based on project) the create view page does not work. It's showing an internal server error.
This is the error I get:
AspNetCoreGeneratedDocument.Views_Actors_Create.ExecuteAsync() in Create.cshtml
#model Actor
#{
ViewData["Title"] = "Add New Actor";
}
<div class="row text">
<div class="col-md-8 offset-2">
<p>
<h1>Add New Actor</h1>
The error is being highlighted on the ViewData line.
My create.cshtml
#model Actor
#{
ViewData["Title"] = "Add New Actor";
}
<div class="row text">
<div class="col-md-8 offset-2">
<p>
<h1>Add New Actor</h1>
</p>
<div class="row">
<div class="col-md-8 offset-2">
<form class="row" asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="mb-3">
<label asp-for="ProfilePictureURL" class="form-label"></label>
<input asp-for="ProfilePictureURL" type="text" class="form-control"/>
<span asp-validation-for="ProfilePictureURL" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="FullName" class="form-label"></label>
<input asp-for="FullName" type="text" class="form-control"/>
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Bio" class="form-label"></label>
<input asp-for="Bio" type="text" class="form-control"/>
<span asp-validation-for="Bio" class="text-danger"></span>
</div>
<div class="mb-3">
<input type="submit" value="Create" class="btn btn-outline-success float-end"/>
<a class="btn btn-outline-secondary" asp-action="Index"> Show All</a>
</div>
</form>
</div>
</div>
</div>
</div>
This is my ActorsController.cs:
using eTickets.Data;
using eTickets.Data.Services;
using Microsoft.AspNetCore.Mvc;
namespace eTickets.Controllers
{
public class ActorsController : Controller
{
private readonly IActorsService _service;
public ActorsController(IActorsService service)
{
_service = service;
}
public async Task<IActionResult> Index()
{
IEnumerable<Models.Actor>? data = await _service.GetAll();
return View(data);
}
public IActionResult Create()
{
return View();
}
}
}
I am using .NET 6 and Visual Studio version 17.2.5.
What could be the problem? Thanks in advance

Auto Age Calculation Field View In Html Form

I am trying to auto calculate the field for age in my asp.net mvc form and post it to the form. I am using datetimepicker to derive the date of birth. Does anyone know how to calculate it just by using the date of birth and post it straight to the forms? Here is my view:
<script language="javascript">
$(document).ready(function () {
// DateA
$('#JSDateA')
.datetimepicker({ format: 'YYYY-MM-DD' });
<form asp-controller="Admin" asp-action="Edit"
method="post">
<div class="form-group row">
<div class="offset-sm-2 col-sm-5 ">
Update User
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" asp-for="Dob">Birth Date :</label>
<div class="col-sm-5">
<input asp-for="Dob" asp-format="{0:yyyy-MM-dd}"
class="form-control" placeholder="YYYY-MM-DD" />
</div>
#{
// TODO: L09 Task 4d - Validation Message for Dob
}
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Age">Age :</label>
<div class="col-sm-5">
<input type="text" id="age" asp-for="Age" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-6">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
#if (ViewData["Message"] != null)
{
<div class="form-group row">
<div class="offset-sm-2 col-sm-6">
<div class="alert alert-#ViewData["MsgType"]">
#Html.Raw(ViewData["Message"])
</div>
</div>
</div>
}
</form>
You can calculate age using js. By setting change event, calculate date and put it to age text field. Try this
$(document).ready(function(){
$("#txtDOB").change(function(){
var dob = $("#txtDOB").val();
if(dob != null || dob != ""){
$("#age").val(getAge(dob));
}
});
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
}
});
Here is a example fiddle for you.
Before resolve your issue,you need know the following things:
1.If Dob in your model is type of DateTime,it will generate <input type="date">,you need set the html type="text",otherwise you will have two datepicker,one belongs to jquery ui,the other belongs to the default html5 datepicker.
2.jquery set input text value by using val().
3.You do not have any html element which has id="JSDateA",so what you did will never work.
Working Demo:
Model:
public class TestVM
{
public DateTime Dob { get; set; }
public int Age { get; set; }
}
View:
<form asp-controller="Admin" asp-action="Edit"
method="post">
<div class="form-group row">
<div class="offset-sm-2 col-sm-5 ">
Update User
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" asp-for="Dob">Birth Date :</label>
<div class="col-sm-5">
<input asp-for="Dob" asp-format="{0:yyyy-MM-dd}"
class="form-control" placeholder="YYYY-MM-DD" type="text" />
#*add type="text"*#
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Age">Age :</label>
<div class="col-sm-5">
<input type="text" id="age" asp-for="Age" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-6">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
#if (ViewData["Message"] != null)
{
<div class="form-group row">
<div class="offset-sm-2 col-sm-6">
<div class="alert alert-#ViewData["MsgType"]">
#Html.Raw(ViewData["Message"])
</div>
</div>
</div>
}
</div>
</form>
The first way,you could write js like below(by using jquery UI Datepicker Widget):
#section Scripts{
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script language="javascript">
$(document).ready(function () {
$('#Dob')
.datepicker({
format: 'yyyy-MM-DD',
maxDate: '+0d',
yearRange: '1950:2021',
changeMonth: true,
changeYear: true,
onSelect: function (value, ui) {
var today = new Date(),
dob = new Date(value),
age = new Date(today - dob).getFullYear() - 1970;
$('#age').val(age);
}
});
})
</script>
}
Result:
The second way,you could write js like below(by using bootstrap-datetimepicker):
#section Scripts
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">
<script>
$(function () {
$('#Dob').datetimepicker();
$('#Dob').on('dp.change', function (e) {
var value = e.date.format(e.date._f);
var today = new Date(),
dob = new Date(value),
age = new Date(today - dob).getFullYear() - 1970;
$('#age').val(age);
})
});
</script>
}
Result2:

Partial view update on ajax POST redirecting to form's action method

I have created 2 partial views called _ftpsetupDetails.cshtml and _ftpsetupedit.cshtml
On load of the index page i am loading details partial view onto the below div.
now the problem is on post to the controller after save i am returning the ready only mode detail partial view. But instead of loading the partial view or hit done method of ajax it is redirecing the page to /FT/Edit url with detail partial view html on it. How to make sure the page is not redirected? what am i doing wrong?
//Once user clicks on Save button the below code will post the form data to controller
$(document).on("click", "#updateFTP", function () {
$.post("/Ftp/Edit", $('form').serialize())
.done(function (response) {
alert(response.responseText);
});
});
//On page load i am loading the partialview container witih read only view
LoadAjaxPage("/Ftp/DetailsByOrgId", "organizationId=" + orgId + "&orgType=" + orgType, "#ftpPartialViewContainer");
//On edit button click i am loading the same div container with edit partial view
$(document).on("click", "#editFTP", function () {
// $("#createUserPartialViewContainer").load("/Users/Create?organizationId=" + orgId + "&organizationType=" + orgTypeId);
LoadAjaxPage("/Ftp/Edit", "organizationId=" + orgId + "&orgType=" + orgType, "#ftpPartialViewContainer");
});
<div id="ftpPartialViewContainer">
</div>
<!--Details HTML partial view code-->
<div class="card shadow mb-3">
<div class="card-header">
<p class="text-primary m-0 font-weight-bold"> FTP Setup</p>
</div>
<div class="card-body">
<div class="row">
<div class="col">
<label for="Name" class="control-label">Name</label>
<input asp-for="Name" class="form-control" readonly />
</div>
</div>
<div class="row">
<div class="col">
<label for="Password" class="control-label">Password</label>
<input asp-for="Password" class="form-control" readonly />
</div>
</div>
<div class="row">
<div class="col">
<input type="submit" value="Edit" class="btn btn-primary" id="editFTP" />
</div>
</div>
</div>
</div>
<!--Edit HTML partial view code-->
#model MyProject.Models.Ftp
#if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
#using (Html.BeginForm("Edit", "ftp", FormMethod.Post,))
{
#Html.ValidationSummary(true, "Please fix the errors")
<div class="card shadow mb-3">
<div class="card-header">
<p class="text-primary m-0 font-weight-bold"> FTP Setup</p>
</div>
<div class="card-body">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Pkid" />
<input type="hidden" asp-for="ConnectedTo" />
<input type="hidden" asp-for="ConnectedToType" />
<div class="row">
<div class="col">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="col">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary " id="updateFTP" />
</div>
</form>
</div>
</div>
}

Getting error when click in my second post for the single page

When I am trying to open first post in single page, it's opening and when trying to open my second post in single page it;s showing "Trying to get property 'title' of non-object"
Here is code
FrontendController
public function singlePost($slug)
{
$post= Post::where('slug', $slug)->first();
return view('single')->with('post', $post)
->with('title', $post->title)
->with('settings', Setting::first())
->with('categories', Category::take(4)->get());
}
single.blade.php
in that I am using same frontend controller for same page
#extends('layouts.frontend')
#section('content')
<div id="product-post">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="heading-section">
<img src="{{$post->featured}}" alt="" />
</div>
</div>
</div>
<div id="single-blog" class="page-section first-section">
<div class="container">
<div class="row">
<div class="product-item col-md-12">
<div class="row">
<div class="col-md-8">
<div class="product-content">
<div class="product-title">
<h3>{{$post->title}}</h3>
<span class="subtitle">4 comments</span>
</div>
<p>
{!! $post->content!!}
</p>
</div>
<div class="leave-form">
<form action="#" method="post" class="leave-comment">
<div class="row">
<div class="name col-md-4">
<input type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="email col-md-4">
<input type="text" name="email" id="email" placeholder="Email" />
</div>
<div class="subject col-md-4">
<input type="text" name="subject" id="subject" placeholder="Subject" />
</div>
</div>
<div class="row">
<div class="text col-md-12">
<textarea name="text" placeholder="Comment"></textarea>
</div>
</div>
<div class="send">
<button type="submit">Send</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
You have to check whether the value is coming from table or not before getting exact column value. In that case if your table return empty result you can redirect it to 404 page.
Please refer the code below :
public function singlePost($slug)
{
$post= Post::where('slug', $slug)->first();
if($post) {
return view('single')->with('post', $post)
->with('title', $post->title)
->with('settings', Setting::first())
->with('categories', Category::take(4)->get());
} else {
// You can redirect to 404 page
}
}

Failed to load resource: the server responded with a status of 500 (Internal Server Error) dynamic api

downloaded latest(3.0) boilerplate with zero.
Followed up the task creator application implementation on codeproject.com
I have added simple entity (Clients) instead of tasks.
The displaying of tasks work fine. However, when I try to add a new client the it seems that the dynamic api is not available and I get the following error:
ClientsController:
`[AbpMvcAuthorize]
public class ClientsController : MyAppControllerBase
{
private readonly IClientAppService _clientService;
public ClientsController(IClientAppService clientService)
{
_clientService = clientService;
}
public async Task<ViewResult> Index(GetAllClientsInput input)
{
var output = await _clientService.GetAll(input);
var model = new Web.Models.Clients.IndexViewModel(output.Items);
return View("Index", model);
}
public async Task Create(CreateClientInput input)
{
await _clientService.Create(input);
}
public async Task Delete(CreateClientInput input)
{
await _clientService.Create(input);
}
}`
Index.js:
(function() {
$(function() {
var _clientService = abp.services.app.client;
var _$modal = $('#ClientCreateModal');
var _$form = _$modal.find('form');
_$form.validate();
_$form.find('button[type="submit"]').click(function (e) {
e.preventDefault();
if (!_$form.valid()) {
return;
}
var client = _$form.serializeFormToObject(); //serializeFormToObject is defined in main.js
abp.ui.setBusy(_$modal);
_clientService.create(client).done(function () {
_$modal.modal('hide');
location.reload(true); //reload page to see new user!
}).always(function () {
abp.ui.clearBusy(_$modal);
});
});
_$modal.on('shown.bs.modal', function () {
_$modal.find('input:not([type=hidden]):first').focus();
});
});
})();
Index.cshtml
#section scripts
{
<environment names="Development">
<script src="~/js/views/clients/Index.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="~/js/views/clients/Index.min.js" asp-append-version="true"></script>
</environment>
}
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="header">
<h2>
#L("Clients")
</h2>
<ul class="header-dropdown m-r--5">
<li class="dropdown">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<i class="material-icons">more_vert</i>
</a>
<ul class="dropdown-menu pull-right">
<li>Action</li>
<li>Another action</li>
<li>Something else here</li>
</ul>
</li>
</ul>
</div>
<div class="body table-responsive">
<table class="table">
<thead>
<tr>
<th>#L("UserName")</th>
<th>#L("FullName")</th>
<th>#L("EmailAddress")</th>
<th>#L("IsActive")</th>
</tr>
</thead>
<tbody>
#foreach (var user in Model.Clients)
{
<tr>
<td>#user.FirstName</td>
<td>#user.LastName</td>
<td>#user.Email</td>
<td>#user.Mobile</td>
</tr>
}
</tbody>
</table>
<button type="button" class="btn btn-primary btn-circle waves-effect waves-circle waves-float pull-right" data-toggle="modal" data-target="#ClientCreateModal">
<i class="material-icons">add</i>
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="ClientCreateModal" tabindex="-1" role="dialog" aria-labelledby="ClientCreateModalLabel" data-backdrop="static">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form name="userCreateForm" role="form" novalidate class="form-validation">
<div class="modal-header">
<h4 class="modal-title">
<span>#L("CreateNewClient")</span>
</h4>
</div>
<div class="modal-body">
<div class="form-group form-float">
<div class="form-line">
<input class="form-control" type="text" name="FirstName" required maxlength="#AbpUserBase.MaxUserNameLength" minlength="2">
<label class="form-label">#L("FirstName")</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" name="LastName" class="form-control" required maxlength="#AbpUserBase.MaxNameLength">
<label class="form-label">#L("LastName")</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" name="Mobile" class="form-control" required maxlength="#AbpUserBase.MaxSurnameLength">
<label class="form-label">#L("Mobile")</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="email" name="Email" class="form-control" required maxlength="#AbpUserBase.MaxEmailAddressLength">
<label class="form-label">#L("Email")</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default waves-effect" data-dismiss="modal">#L("Cancel")</button>
<button type="submit" class="btn btn-primary waves-effect">#L("Save")</button>
</div>
</form>
</div>
</div>
</div>
client service :
[AbpAuthorize(PermissionNames.Pages_Tenants)]
public class ClientAppService : ApplicationService, IClientAppService
{
private readonly IRepository<Client> _clientRepository;
public ClientAppService(IRepository<Client> clientRepository)
{
_clientRepository = clientRepository;
}
public async Task<ListResultDto<ClientListDto>> GetAll(GetAllClientsInput input)
{
var clients = await _clientRepository
.GetAll().ToListAsync<Client>();
return new ListResultDto<ClientListDto>(
ObjectMapper.Map<List<ClientListDto>>(clients));
}
public async Task Create(CreateClientInput input)
{
var task = ObjectMapper.Map<Client>(input);
await _clientRepository.InsertAsync(task);
}
}
the server does not get hit at all on the create action.
any idea what I am missing?
I think there's a misunderstanding with IMustHaveTenant interface. When you derive an entity from IMustHaveTenant you cannot use that entity in host environment. The host has no tenant id. As far as i understand clients are belonging to tenants. So what you have to do is, remove the Clients page from host menu. Whenever you want to see clients of tenants, just use impersonation.
To show/hide specific menu items you can use requiredPermissionName. A permission can be configured to use just for tenants/host/both. So create a new permission which is configured to be used for tenants. Set that permission while you create new MenuItemDefinition for clients page. That's it!
Read => https://aspnetboilerplate.com/Pages/Documents/Navigation?searchKey=navigation#registering-navigation-provider

Resources