Date picker in mvc3 with razor view engine - asp.net-mvc

I am using mvc3 and razor is my view engine how i get date picker with out using scripts in my
view.

You can create a script in the directory scripts of your project.
Basic example:
$(document).ready(function () { $("#datepicker").datepicker({ });});
in your view:
#model YourProjectName.Models.User
....
<div class="editor-field">
#Html.TextBoxFor(model => model.Dateadd, new { #Value = DateTime.Now, id = "datepicker" })
#Html.ValidationMessageFor(model => model.Dateadd)
</div>

I think you are going to have to use a script, check out jqueryui datepicker. Its a nice easy to use library and supports theming

I answered here, check it out: http://forums.asp.net/post/4647234.aspx
Basically you're using a template with a script in one location and calling it with EditorFor.

To advisers here: it's a bad practice to use scripts inside partial views (templates).
In my case it does not work at all. Because accessing jquery happens before it's included as js file.
Plus you cannot predict where exactly you would put this datepicker control.
Also, you will have this "ready" block for every editor on the page.
RenderSection would bring some order to all this, but it does not work for partialviews and templates.
So just move javascript code from a template (partialview) to a view.

#model Nullable<System.DateTime>
#if ( Model.HasValue ) {
#Html.TextBox( "" , String.Format( "{0:yyyy-MM-dd HH:mm}" , Model.Value ) , new {
#class = "textbox" , #style = "width:400px;" } )
}
else {
#Html.TextBox( "" , String.Format( "{0:yyyy-MM-dd HH:mm}" , DateTime.Now ) , new {
#class = "textbox" , #style = "width:400px;" } )
}
#{
string name = ViewData.TemplateInfo.HtmlFieldPrefix;
string id = name.Replace( ".", "_" );
}
<script type="text/javascript">
$(document).ready(function () {
$("##id").datepicker
({
dateFormat: 'dd/mm/yy',
showStatus: true,
showWeeks: true,
highlightWeek: true,
numberOfMonths: 1,
showAnim: "scale",
showOptions: {
origin: ["top", "left"]
}
});
});
</script>

If you use an Editor Template for the DateTime type, you can use an HTML5 date picker (i.e. <input type="date" />). Essentially you put a view called DateTime.cshtml in a folder called Views/Shared/EditorTemplates, then you can style the editor however you like. One example is in an answer here.

Related

MVC View. List of strings. Conditionally use DateTime EditorTemplate on List Item

The View is an 'Application Form'
The model is an 'Application' object.
The Application object contains a Person object and an array of Question objects.
Each question has:
A text field containing the question
A numeric field containing the question type (1= number , 2 = string,3=Date etc)
A text field for the response. The response field is preloaded with an example (In the case of Dates it is DateTime.Now.ToShortDateString())
The View has a form containing the Person details and a table which contains the question list. The Applicant fills in the Response fields and submits. This works.
I now want to present the Date type questions with a DatetimePicker.
Using a Razor 'if' statement on the questionType field I can separate out the datetime questions from the others in the list display.
For the Datetype questions I want to call a DateTime Picker EditorTemplate.
<td>
<div class="col-md-10">
#{
if (Model.Responses[i].QuestionTypeId == 3)
{
#Html.EditorFor(p => p.Responses[i].Response,"DateTime")
#Html.ValidationMessageFor(p => p.Responses[i].Response)
}
else
{
#Html.TextBoxFor(p => p.Responses[i].Response)
#Html.ValidationMessageFor(p => p.Responses[i].Response)
}
}
#*#Html.TextBoxFor(p => p.Responses[i].Response)
#Html.ValidationMessageFor(p => p.Responses[i].Response)*#
</div>
</td>
To get the DateTime.cshtml EditorTemplate to run, I had to make the model type a string.
Although it gets called, it doesn't execute the datepicker javascript.
I assume this is because the underlying Model field type is a string.
I tried making a date out of the string in the Template and passing the date into the Template TextBox call but this had no effect.
Is there a way past this?
EditorTemplate code currently is:
#model System.String
#{ DateTime myDate = DateTime.Parse(Model);}
#Html.TextBox("", myDate,new { #class = "datePicker" ,
})
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
$(".datePicker").datepicker({
showOn: "button",
buttonImage: "/images/calendar-icon.png",
buttonImageOnly: true,
buttonText: "Select date"
});
});
</script>
}

Ajax.ActionLink alternative with mvc core

In MVC5 there is #Ajax.ActionLink that is useful to update just a partial view instead of reloading the whole View. Apparently in MVC6 is not supported anymore.
I have tried using #Html.ActionLink like the following but it doesn't update the form, it return just the partial view:
View:
#Html.ActionLink("Update", "GetEnvironment", "Environments", new { id = Model.Id }, new
{
data_ajax = "true",
data_ajax_method = "GET",
data_ajax_mode = "replace",
data_ajax_update = "environment-container",
#class = "btn btn-danger"
})
control:
public async Task<ActionResult> GetEnvironment(int? id)
{
var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
return PartialView("_Environment",environments);
}
Partial view:
#model PowerPhysics.Models.Environments
this is a partial view
Then I tried using ViewComponents. When the page loads the component works correctly but I don't understand how to refresh just the component afterward (for example with a button):
View:
#Component.InvokeAsync("Environments", new { id = Model.Id }).Result
component:
public class EnvironmentsViewComponent : ViewComponent
{
public EnvironmentsViewComponent(PowerPhysics_DataContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(int? id)
{
var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
return View(environments);
}
}
How can I update just a part of a view by using PartialViews in MVC6?
You can use a tag as follows:
<a data-ajax="true"
data-ajax-loading="#loading"
data-ajax-mode="replace"
data-ajax-update="#editBid"
href='#Url.Action("_EditBid", "Bids", new { bidId = Model.BidId, bidType = Model.BidTypeName })'
class="TopIcons">Link
</a>
Make sure you have in your _Layout.cshtml page the following script tag at the end of the body tag:
<script src="~/lib/jquery/jquery.unobtrusive-ajax/jquery.unobtrusive-ajax.js"></script>
ViewComponent's are not replacement of ajaxified links. It works more like Html.Action calls to include child actions to your pages (Ex : Loading a menu bar). This will be executed when razor executes the page for the view.
As of this writing, there is no official support for ajax action link alternative in aspnet core.
But the good thing is that, we can do the ajaxified stuff with very little jQuery/javascript code. You can do this with the existing Anchor tag helper
<a asp-action="GetEnvironment" asp-route-id="#Model.Id" asp-controller="Environments"
data-target="environment-container" id="aUpdate">Update</a>
<div id="environment-container"></div>
In the javascript code, just listen to the link click and make the call and update the DOM.
$(function(){
$("#aUpdate").click(function(e){
e.preventDefault();
var _this=$(this);
$.get(_this.attr("href"),function(res){
$('#'+_this.data("target")).html(res);
});
});
});
Since you are passing the parameter in querystring, you can use the jQuery load method as well.
$(function(){
$("#aUpdate").click(function(e){
e.preventDefault();
$('#' + $(this).data("target")).load($(this).attr("href"));
});
});
I add ajax options for Anchor TagHelper in ASP.NET MVC Core
you can see complete sample in github link :
https://github.com/NevitFeridi/AJAX-TagHelper-For-ASP.NET-Core-MVC
after using this new tagHelper you can use ajax option in anchor very easy as shown below:
<a asp-action="create" asp-controller="sitemenu" asp-area="admin"
asp-ajax="true"
asp-ajax-method="get"
asp-ajax-mode="replace"
asp-ajax-loading="ajaxloading"
asp-ajax-update="modalContent"
asp-ajax-onBegin="showModal()"
asp-ajax-onComplete=""
class="btn btn-success btn-icon-split">
<span class="icon text-white-50"><i class="fas fa-plus"></i></span>
<span class="text"> Add Menu </span>
</a>
Use tag helpers instead and make sure to include _ViewImport in your views folder.
Note: Make sure to use document.getElementsByName if there are several links pointing to different pages that will update your DIV.
Example - Razor Page
<script type="text/javascript" language="javascript">
$(function () {
var myEl = document.getElementsByName('theName');
$(myEl).click(function (e) {
e.preventDefault();
var _this = $(this);
$.get(_this.attr("href"), function (res) {
$('#' + _this.data("target")).html(res);
});
});
});
</script>
<a asp-action="Index" asp-controller="Battle" data-target="divReplacable" name="theName" >Session</a>
<a asp-action="Index" asp-controller="Peace" data-target="divReplacable" name="theName" >Session</a>
<div id="divReplacable">
Some Default Content
</div>

How to use datetime picker as editortemplate

How can i use datetime picker in my mvc view .
EditorTemplate : Datetime.cshtml
#model DateTime?
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy"):"", new { #class = "datefield" })
Model :
[Required]
public DateTime DateOfBirth { get; set; }.
Also jquery.ui.all.css is under my solution content>themes>base
Here is the partial view where the datepicker is needed .
#model PersonalDetails`
`
#Html.LabelFor(model => model.DateOfBirth)
#Html.EditorFor(model => model.DateOfBirth, new { #placeholder = "Date Of Birth", #class = "datefield" ,#type="text" })
#Html.ValidationMessageFor(model => model.DateOfBirth)
Here the date field is coming in the format specified in the Datetime editor template. But the calendor image is not coming.
Assume you have editor set up for jQuery datepicker:
#Html.EditorFor(model => model.DateOfBirth, new { #placeholder = "Date Of Birth", #class = "datefield", #type="text" })
Check if your JS code has working properly by browser debugging, your datepicker code should looks like this:
<script type="text/javascript">
$(document).ready(function () {
$(".datefield").datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
showOtherMonths: true,
selectOtherMonths: true,
// other datepicker settings here as you want
});
});
</script>
Then make sure jQuery UI CSS file has included either inside Layout.cshtml or inside head tag on your page, at this step your calendar image should be shown besides date editor:
<link rel="stylesheet" href="~/Content/themes/base/jquery.ui.all.css" type="text/css">
<script src="~/Scripts/jQuery-[version].js" type="text/javascript">
<script src="~/Scripts/jQuery-ui-[version].js" type="text/javascript">
To simplify those script and style declarations, I suggest you learning MVC styles/scripts bundling.
Any suggestions welcome.

Html new lines in kendo grid

I have a kendo grid in mvc with column property .Encoded(false)
In the controller I replaced Environment.NewLine with
<br>
But in the view there is a text instead of real new line. I tried both:
<br> or <br/>
It is not working either. What am I doing wrong?
Finally I solved it myself.
in the Grid:
columns.Bound(m => m.Address).Width(150).Encoded(false).ClientTemplate("#= getHtmlNewLinesString(Address) #");
and in the js:
function getHtmlNewLinesString(text) {
var regexp = new RegExp('\n', 'g');
return text.replace(regexp, '<br>');
}
You can also use css to solve this.
in html file:
col.Bound(c => c.Text)
//.Encoded(false)
.Title("text")
.HtmlAttributes(new { Class = "keepLineBreak" });
in css file:
.keepLineBreak {
white-space: pre-wrap;
}
Reference:
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
The filter is not working in this case because the cell includes <br>.

Options(session variable??) to get set checkbox value with MVC paging and sorting

In my html.beginform I have this checkbox that I want to persist. I'm not sure how to add it to the below ActionLink...or if it is even possible. I thought of using a session variable. If anyone has an example showing how to set a checkbox value in a session variable that would be awesome...or if there is a way to pass it in the ActionLink...that would be cool too.
cheers and thanks in advance
#Html.CheckBoxFor(model=>model.wccrSelection.SendDemand)
#Html.ActionLink("Order",
"Display", new {Model.wccrSelection.WccrId,sortOrder = ViewBag.NameSortParm })
You could use a <form> instead of a link. This way the value of the checkbox will be automatically sent to the controller and you don't need to use any javascript:
#using (Html.BeginForm("Display", null, new { id = Model.wccrSelection.WccrId, sortOrder = ViewBag.NameSortParm }))
{
#Html.CheckBoxFor(model=>model.wccrSelection.SendDemand)
<button type="submit">Order</button>
}
You can use jQuery to add additional parameter for passing checkbox state to your action method as shown below:
Eg.:
#Html.CheckBoxFor(model=>model.wccrSelection.SendDemand, new {#class = "SendDemand"})
#Html.ActionLink("Order",
"Display", new {Model.wccrSelection.WccrId,sortOrder = ViewBag.NameSortParm }, new { #class = "DisplayOrder" })
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
(".DisplayOrder").on.("click",function(){
var href = $(this).attr("href");
if ($(".SendDemand").is(':checked')) {
href = href + "&CheckBoxState=true";
}
else {
href = href + "&CheckBoxState=false";
}
$(this).attr("href", href);
});
});
</script>

Resources