I've spent all day searching high and low for an answer to my problem and just can't find one.
Can someone please suggest a simple way I can get the value of the input field as a parameter in my Ajax call?
I would rather it stayed as an #Ajax.ActionLink call if possible.
Thanks.
<div class="form-group ui-widget">
<input class="form-control" id = "Reference" type = "text" />
</div>
<div>
#Ajax.ActionLink("Select","SelectedReference","Home",
new { reference = ?????????? },
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "Results",
InsertionMode = InsertionMode.Replace,
OnBegin = "OnBeforeReference",
OnFailure = "OnAjaxError",
OnSuccess = "hideReference"
},
new
{
id = "referenceSelectButton",
#class = "btn btn-success"
})
</div>
Can I get the value of the input field as a parameter in my Ajax call?
No, It's not possible to use #Ajax.ActionLink to fulfil your requirements.
Alternatively, You can use jQuery ajax to do this.
Just use a simple button:
<button class="btn btn-success" id="referenceSelectButton">Select</button>
And on button click use jQuery ajax request to do all your work done.
#section Scripts{
<script type="text/javascript">
$('#referenceSelectButton').click(function () {
var referenceVal = $('#Reference').val();
$.ajax('#Url.Action("SelectedReference","Home",new { reference="-1"})'.replace('-1', referenceVal), {
method: 'post',
beforeSend:OnBeforeReference,
success: function (response) {
$('#Results').html(response);
hideReference();
},
error: OnAjaxError,
});
});
</script>
}
I have placed the jquery script code inside #section so that It's placed after jQuery scripts. Hopefully, this will resolve your problem.
Related
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);
}
I just want to make sure this ajax is working to call my controller. But when i click the button nothing happened. Thank you
My view :
<input type="text" id="phonenumber" name="phonenumber" class="form-control" placeholder="Phone number">
<button type="button" id="sendotp" name="sendotp" class="btn btn-primary btn-block">Sign Up</button>
My AJAX :
$(document).ready(function() {
$('#sendotp').click(function(e) {
e.preventDefault();
var phonenumber = $("input[name='phonenumber']").val();
$.ajax({
url: '<?php echo base_url();?>/register',
type:'post',
dataType:'json',
data: {
phonenumber:phonenumber
},
success: function(data) {
}
});
});
});
My Controller :
public function register()
{
if($this->request->getMethod() == 'post'){
$phonenumber = $this->request->getPost('phonenumber');
echo $phonenumber;
}
return view('register/register');
}
My Routes :
$routes->match(['get', 'post'],'/register', 'Home::register');
In your javascript you have you success event empty. So nothing happening is the expected behavior. If you're returning a view in your controller, you must do something with it in your javascript.
marco answer sufficient.
You need also to add
headers: {'X-Requested-With': 'XMLHttpRequest'}
in your ajax call in JQuery
$.ajax({
url: '<?php echo base_url();?>/register',
type:'post',
dataType:'json',
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
phonenumber:phonenumber
},
success: function(data) {
}
});
and in your controller check if its ajax call first before processing anything.
if ($this->request->isAJAX())
{
}
Please refer to isAjax and refer to Ajax JQuery
this is the proper way to handle ajax calls in Codeigniter4 .
I had the same issue I fixed it Like this:
in app/Config/Filter.php make this change:
public $globals = [
'before' => [
'csrf' => ['except' => ['your route or api']]
]
];
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>
I have 2 checkboxes. I need to capture the checkboxes clicked and send it to REST SERVICE, I am able to capture checkboxes clicked at fnt end but I don't know how to capture it in the REST (VB.Net).
Below is the front end file:
<form>
<input type="checkbox" class = "checkBoxProp" id = "1" name="checkBoxProp" value="1">Graph1<br>
<input type="checkbox" class = "checkBoxProp" id = "2" name="checkBoxProp" value="2">Graph4<br>
<input id="btnGetResponse" type="button" value="ClickMe!"/>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("#btnGetResponse").click(function()
{
var ids = $('.checkBoxProp:checked').map(function() {
return this.value;
}).get();
console.log(JSON.stringify(ids.join()));
$.ajax({
type: "POST",
url: "http://localhost:51349/SMS_Rest.svc/v1/usercheckboxes",
data: {ids: ids} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
alert('success');
},
failure: function(response)
{
alert('fail');
}
});
});
So how to capture JSON at REST.
Public Function CheckBoxDetails(ByVal requestData As **WHAT TO WRITE HERE**) As String Implements iSMS_Rest.CheckBoxDetails
// SOME LOGIC
End Function
Your method at server-side should be a POST and you should capture the data from body of the request instead of querystring. So, the argument list should have [FromBody] attribute and it would be abetter way if you can create a input model class with similar structure as the input data and have similar properties, use that object as the parameter to the POST method.
I have been trying to work out how I can get the list of selected checkboxes to work using an ActionLink. I think I need to do something clientside with JavaScript but cannot find the relevant code.
The following code works perfectly using a submit button, posting back the selected id's as an array of id's, but I need to have this on a page with other buttons.
// the view
#foreach (var station in Stations)
{
<input type="checkbox" name="selected" value="#station.StationId" />
}
<input type="submit" value="Save" />
//Controller stub
public ActionResult Action(string [] selected)
I have been stuck on this for hours, so maybe I am looking at this the wrong way.
PS. My first post after many many hours reading and learning here.
SomeButtons or links to post checkboxlist values
Post
//or buttons, helpers and any elements to trigger ajax post...
CheckboxList:
<div id="MyDiv">
#foreach (var station in Stations)
{
<input type="checkbox" name="selected" value="#station.StationId" />
}
</div>
Scripts:
$(document).ready(function() {
$('#someButton').click(function() {
var list = [];
$('#MyDiv input:checked').each(function() {
list.push(this.name);
});
// now names contains all of the names of checked checkboxes
// do something with it for excamle post with ajax
$.ajax({
url: '#Url.Action("Action","Contoller")',
type: 'POST',
data: { Parameters: list},
success: function (result) {
alert("success")!
},
error: function (result) {
alert("error!");
}
}); //end ajax
});
});
Controller:
public ActionResult Action(string [] Parameters)
if I got it right :)
Looks like you are not looking for AJAX post. The easiest way to tackle this is to wrap it in the form and call submit function. Here is what your code should look like:
#using(Html.BeginForm("uraction", "urcontroller", FormMethod.Post, new { id = "formId" })) {
foreach(var station in Stations) {
<input type="checkbox" name="selected" value="#station.StationId" />
}
}
Post
<script>
$(document).ready(function() {
$('#postBtn').click(function() {
$('#formId').submit();
}
}
</script>