get html 5 date input field and pass to .net controller - razor

On my razor page, I have a simple date picker that looks like this:
<input type="date" name="lessonsStart">
How would I go about getting the value of that and sending it to my controller?
Whenever I send data to my controller from a razor page, the format always looks something like this:
<a asp-action="LessonIndex" asp-route-id="#item.Id">#Html.DisplayFor(modelItem => item.Name)</a>
which sends an "item.Id" to my controller called LessonIndex().
So I'm not sure how I'd get the date value and send it.
The controller looks like this:
public IActionResult LessonIndex(datetime startDate) {
var response = getLessons(startDate);
return response.Results;
}
Is there a specific format I need to use?
Note that the date is not used in a model, it just needs to be sent to a controller.
Thanks!

Assuming this is related to mvc the controller would have a method associated with the post that you would perform to get the data from the form back to the controller. This uses javascript to post data to your LessonIndex() method.
<!--top of your page.-->
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<input type="date" id="lessonStart" name="lessonStart" />
<input type="Submit" id="PostButton" name="PostButton" Value="Go" />
#section Scripts{ // razor section at the bottom of mvc page 'cshtml'.
<script type="javascript">
$(function(){
$("#PostButton").click(function(){
var url = '#Url.Action("LessonIndex", "Lesson")'; //assuming controller is named Lesson
var date= new Date(this.value).ToDateString();
$.ajax({
url: url,
type: "POST",
data: "lessonStart=" + date,
headers:{
"RequestVerificationToken": '#GetAntiXsrfRequestToken()'
},
success: function(response){
console.log(response);
},
error: function(e){
console.log(e.error);
}
});
});
}
</script>
}
this also assumes that the method looks like this
public class LessonController : Controller{
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult LessonIndex(DateTime lessonStart){
var response = getLessons(lessonStart);
return View(response.results);
}
}

" Note that the date is not used in a model, it just needs to be sent to a controller. "
You could use the ajax to pass the date as QueryString to the method in the controller.
Here is the test example
<input type="date" name="lessonsStart" id="lessonsStart">
#section Scripts
{
<script type="text/javascript">
$("#lessonsStart").change(function () {
var inputDate = new Date(this.value).toDateString();
$.ajax({
type: "post",
url: "/ControllerName/lessonindex?startdate=" + inputDate,
success: function () { }
});
});
</script>
}
The method in controller
[HttpPost]
public IActionResult LessonIndex(DateTime startDate)
{
return Json(startDate);
}

<div class="demo-section k-content">
<h4>Remind me on</h4>
#(Html.Kendo().DateTimePicker()
.Name("datetimepicker")
.Value(DateTime.Now)
.HtmlAttributes(new { style = "width: 100%", title = "datetimepicker" })
.DateInput()
)
</div>

Related

How can I define a route for search process in ASP.NET MVC?

I have a problem about defining a route with respect to a search process in the controller part of ASP.NET MVC.
What I want to do is to get this URL which is defined below after I click a search button in the form.
Blog/Search?searchKeyword=banana
I created a sample form but I have no idea how to define the url in its action. How can I do that?
Here is the code related with a form code snippet which is shown below.
<form action="Blog/Search/" method="get">
<input type="text" name="searchKeyword">
<button type="submit"><i class="bi bi-search"></i></button>
</form>
Here is the search function which is defined in the controller part shown below.
[HttpGet]
[Route("Blog/Search/{searchKeyword}")]
public ActionResult BlogSearch(string search_string, int Sayfa = 1)
{
var searchList = db.Blog.Include("Category").Where(
x => x.Content.Contains(search_string)).OrderByDescending(x => x.BlogId).ToPagedList(Page, 5);
return View(searchList);
}
Here is my answer shown below.
js file
<script type="text/javascript">
$(document).ready(function () {
$("#searchButton").click(function () {
var searchKeyword = $("#searchKeyword").val();
$.ajax({
url: '/Home/BlogSearch/',
data: {searchKeyword: searchKeyword},
type: 'POST'
});
});
})
</script>
BlogSearch Process
public ActionResult BlogSearch(string search_string, int Sayfa = 1)
{
var searchList = db.Blog.Include("Kategori").Where(
x => x.Icerik.Contains(search_string)).OrderByDescending(x => x.BlogId).ToPagedList(Sayfa, 5);
return View(searchList);
}

Controller Void Method On Button Click Using Ajax. ASP.NET

So I have a .ASP MVC Web Application project. I want to run a void method from the controller class when I press a button using AJAX. No variable input or output data needed. I just want to create a pdf file and save it on my local machine.
Right now, nothing at all happens when I click the button. I don't think the ajax script works, 0 connection.
This is my Controller method:
[HttpPost]
public void Test()
{
string dok = System.IO.File.ReadAllText("C:\\Users\\axel\\Desktop\\Repo\\Cert\\employee_regular.html");
var Renderer = new IronPdf.HtmlToPdf();
var HtmlTemplate = dok;
var Pdf = Renderer.RenderHtmlAsPdf(HtmlTemplate);
Pdf.SaveAs("C:\\Users\\axel\\Desktop\\Repo\\Cert\\Arbetsgivarintyg_vanlig_heltid.pdf");
}
This is my Index.cshtml file
#{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-12">
<h2>Request employement certificate</h2>
<input type="button" onclick="BtnClick()" value="Click me" />
</div>
</div>
<script>
function BtnClick() {
$ajax({
url: "/Home/Test",
method: "POST",
success: function () {
alert("ok");
},
error: function () {
alert("not ok")
}
})
}
</script>
Really happy for any help
Well there can be several reasons why your code is not working.
First Make sure you are actually able to make a call to a function, Just simply add simple alert message before calling the ajax and see if the alert triggers.
The second thing is to validate url replace the hardcoded url and add url using URL helper.
I would recommend you to make a function as JsonResult Instead of Void, because an exception can happen when creating pdf. [This change is optional but I do recommend it]
So after all the changes your code would look something like this
#{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-12">
<h2>Request employement certificate</h2>
<input type="button" onclick="BtnClick()" value="Click me" />
</div>
</div>
<script>
function BtnClick() {
$ajax({
alert("Funciton is working"); // change confirm function is working
url: "#Url.Action("Test","Home")", // change using Url Helper to create valid URL
method: "POST",
success: function (data) {
if (data == true)
{
alert("pdf created sucessfully ok");
}
else
{
alert("exception happend when creating pdf not ok");
}
},
error: function () {
alert("not ok")
}
})
}
</script>
Your Back End would look something like this
[HttpPost]
public JsonResult Test()
{
try {
string dok = System.IO.File.ReadAllText("C:\\Users\\axel\\Desktop\\Repo\\Cert\\employee_regular.html");
var Renderer = new IronPdf.HtmlToPdf();
var HtmlTemplate = dok;
var Pdf = Renderer.RenderHtmlAsPdf(HtmlTemplate);
Pdf.SaveAs("C:\\Users\\axel\\Desktop\\Repo\\Cert\\Arbetsgivarintyg_vanlig_heltid.pdf");
return Json(true, JsonRequestBehavior.AllowGet);
}
catch(Exception ex) {
return Json(false, JsonRequestBehavior.AllowGet);
}
}

Partial view not serializing in ajax Post request MVC

Implementing the auto save functionality for my page. so after certain interval calling action Autosave(). But my page having begin form including the Partial view. The code for after interval call is working fine.
<script type="text/javascript">
window.setInterval(function () {
var form = $("#addpost");
$.ajax({
url: '#Url.Action("AutoSavePostAction", "MyControllerName")',
data: form.serialize(),
type: 'POST',
success: function (data) {
$("#Id").val(data);
}
});
}, 30000);
View is :
#using (Html.BeginForm("SavePostAction", "MyControllerName", FormMethod.Post, new { enctype = "multipart/form-data", id="addpost" }))
{
.................
#Html.Partial("_TextPostPartial", Model);
.................
}
SavePostAction is after calling submit. On this submission, getting the value from Partial view, which is not an issue.
But in ajax call somehow partial view does not included in serialization.
Here _TextPostPartial having CKEditor which is strongly bind with Model.
Like Partial view having :
<textarea id="Description" name="Description">#Html.Raw(Model.Description)</textarea>
Edited:
[HttpPost]
public ActionResult AutoSavePostAction(PostDTO postDTO, FormCollection postFormCollection)
{
}
[HttpPost]
[MemberFunction]
public ActionResult SavePostAction(PostDTO postDTO, FormCollection postFormCollection)
{
}
You need to assign the value of the CKEditor to the input before serializing the form data
window.setInterval(function () {
$("#Description").val(CKEDITOR.instances['Description'].getData()); // add this
var form = $("#addpost");
$.ajax({
url: '#Url.Action("AutoSavePostAction", "MyControllerName")',
data: form.serialize(),
type: 'POST',
success: function (data) {
$("#Id").val(data);
}
});
}, 30000);

Autocomplete for textbox in mvc

This is my view and controller. I have converted code from c# to vb the code was working perfectly in C# but i dont know why this java script is not working in vb. I started debugging but controllers never get called when i type something in search box.
Code for View
#ModelType PrudentHealthCare.Product
#Code
Layout = Nothing
End Code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Search</title>
</head>
<body>
<div>
#Using (Html.BeginForm())
#Html.HiddenFor(Function(model) model.id)
#<input type="text" id="search" placeholder="Search for a product" required />
#<input type="submit" value="Go" id="submit" />
End Using
</div>
</body>
</html>
<link href="~/Content/AutoComplete/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/AutoComplete/jquery-ui.js"></script>
<script src="~/Content/AutoComplete/jquery-1.9.1.js"></script>
<script type="text/javascript">
var url = '#Url.RouteUrl( "DefaultApi" , New With { .httproute = "", .controller = "ProductApi" })';
$('#search').autocomplete({
source: function (request, response) {
$.ajax({
url: url,
data: { query: request.term },
dataType: 'json',
type: 'GET',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Description,
value: item.Id
}
}));
}
})
},
select: function (event, ui) {
$('#search').val(ui.item.label);
$('#Id').val(ui.item.value);
return false;
},
minLength: 1
});
</script>
ProductApiController
Imports System.Web.Mvc
Namespace Controllers
Public Class ProductApiController
Inherits Controller
<HttpGet>
Public Function GetProducts(Optional query As String = "") As IEnumerable(Of Product)
Dim xyz As String
xyz = query
End Function
End Class
End Namespace
jQuery UI has an AutoComplete widget. The autocomplete widget is quite nice and straight forward to use. In this post, how to integrate the AutoComplete widget with an ASP.NET MVC application.
The first step is to add the jQuery scripts and styles. With ASP.NET MVC 4, the following code does the work:
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
Using the AutoComplete widget is also simple. You will have to add a textbox and attach the AutoComplete widget to the textbox. The only parameter that is required for the widget to function is source. For this example, we will get the data for the AutoComplete functionality from a MVC action method.
$(document).ready(function () {
$('#tags').autocomplete(
{
source: '#Url.Action("TagSearch", "Home")'
});
})
In the above code, the textbox with id=tags is attached with the AutoComplete widget. The source points to the URL of TagSearch action in the HomeController: /Home/TagSearch. The HTML of the textbox is below:
<input type="text" id="tags" />
When the user types some text in the textbox, the action method - TagSearch is called with a parameter in the request body. The parameter name is term. So, your action method should have the following signature:
public ActionResult TagSearch(string term)
{
// Get Tags from database
string[] tags = { "ASP.NET", "WebForms",
"MVC", "jQuery", "ActionResult",
"MangoDB", "Java", "Windows" };
return this.Json(tags.Where(t => t.StartsWith(term)),
JsonRequestBehavior.AllowGet);
}

Pass dropbox value to a HttpGet action submit button click?

Basically I'm trying to pass the value of my dropbox to a get action.
The submit-button re-directs to the correct action , but what is the correct way to add the value of the dropbox with the re-direction?
My view:
#model TrackerModel
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Get, new { ???}))
{
<div>
<strong>#Html.LabelFor(m => m.CustomerName)</strong>
#Html.TextBoxFor(m => m.CustomerName, new { type = "hidden", #class = "customer-picker" })
</div>
<button class="styledbutton" onclick="window.location.href='/Tracker/Index'">Cancel</button>
<button type="submit" value="submit" id="selectCustomer-button" class="styledbutton">Submit</button>
}
[HttpGet]
public ActionResult MyAction(IPrincipal user, Tracker model)
Customer-picker
$(document).ready(function () {
CustomerPicker();
});
function CustomerPicker() {
$('.customer-picker').select2({
placeholder: 'Select customer',
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: '/JsonData/GetCustomers',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
query: term // search term
};
},
results: function (data) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return { results: data };
}
},
formatResult: function (data) {
return data;
},
formatSelection: function (data) {
return data;
}
});
}
I was expecting the value to be within my Tracker model parameter in the action, but this returns nulls. Also I'm not sure what to place in the "new" parameter in the form tag?
I also tried the following but all I get returning to the controller is text:"".
#Html.TextBoxFor(m => m.CustomerName, new { type = "hidden", #id = "selectedCustomer", #class = "customer-picker" })
<script type="text/javascript">
$(function () {
$("#Form1").submit(function (e) {
alert("boo");
e.preventDefault();
var selectCustValue = $("#selectedCustomer").val();
$.ajax({
url: '/CalibrationViewer/SentMultipleCalsToCustomer',
data: { text: selectCustValue }
});
});
});
OK got it,
var selectCustValue = $("#s2id_CustomerName span").text();
Found another piece of code the used the customer-picker and the javascript associated with view used the above.
I viewed the page source and it still show's both id and name as CustomerName, it has something to do with the "Select 2" helper.
I may get slated for marking this as the answer, considering I should have figured it out earlier, but there you have it !