Ajax passing data to ASP.NET controller - javascript

I'm attempting to run an ajax request on my ASP.NET web app where I pass a search term and receive some data back
<div class="form-group">
<input type="text" id="orgSearch" placeholder="Search organisation by name..." class="form-control" name="search" autocomplete="off" data-controller="#Model.ControllerName" data-target-property="#Model.LookaheadProperty">
</div>
<script>
$(document).ready(function () {
var form = document.getElementById("orgSearch");
form.addEventListener("keyup", function (event) {
event.preventDefault();
var search = document.getElementById("orgSearch").value;
$.ajax({
type: "GET",
url: "Organisation/Search?search=" + search,
success: function (object) {
console.log(object);
}
});
});
});
</script>
And then here's the method in my OrganisationsController.cs class
public class OrganisationsController : Controller
{
[HttpGet]
public async Task<IActionResult> Search([FromRoute] string search)
{
var items = await _organisationsService.SearchAsync(search);
return Ok(items);
}
}
However, when I try it the ajax call isn't even being made (It's generating a 404 error on the console log) and I can't work out how to pass the search parameter. Does anyone have any suggestions?

Fix ajax url from organization to organizations and add "/" in the beginning:
url: "/Organisations/Search?search=" + search,
your action then
public async Task<IActionResult> Search([FromQuery] string search)
{
......
}
You can also try to use [FromUri] instead [FromQuery]
And by the way, if your version Mvc supports attribute routing, it maybe better to change action to this:
[Route("~/Organizations/Search/{search}")]
public async Task<IActionResult> Search( string search)
{
....
}
in this case your ajax url:
url: "/Organisations/Search/" + search,

Related

Why this JQuery function just works with post?

Why this JQuery function works with post? But not with get? I don't want to change anything in my database just to return some information...It seems that like I am passing parameters it just recognize type: post in Ajax even if my intention is not to change anything. If I don't use type:"post" my parameter in the controller action is going to be null.
$(document).ready(function () {
$(".link").click(function () {
var grad = $(".link").data("graduate")
$.ajax({
type: "post",
url: $(".link").data("url"),
data: JSON.stringify( { graduate: grad }),
contentType: "application/json; charset=utf-8"
})
$("#myModal").modal("show");
})
})
This is my controller:
public ActionResult PopulateModal(CMIPGraduateVM graduate)
{
return PartialView(graduate);
}
You can send data in the body of a POST request. You can only pass data with a GET request by using URL parameters, e.g. url.com?this=that&so=on
Add [HttpPost] to your controller method to allow it to accept posted data.
[HttpPost]
public ActionResult PopulateModal(CMIPGraduateVM graduate)
{
return PartialView(graduate);
}
And CMIPGraduateVM needs to be a class that has the graduate property whose type matches the structure that you're providing with the grad variable (var grad = $(".link").data("graduate"); not sure if this is a string or bool or object, etc).

How do i submit form via ajax?

i'm trying to submit forms without post back via ajax ..my code doesn't work
whats wrong in my script?
i'm new to ajax..help me with ajax scripts..
below is my code
note: i have two submit buttons with in single view. I want to make ajax call for both submit actions
my view
#model AjaxEF.Models.Customer
#using (Html.BeginForm("Index", "Main", FormMethod.Post,new { id="idForm"}))
{
#Html.EditorForModel()
<br />
<input type="submit" name="save" value="Save" />
<input type="submit" name="cancel" value="Cancel" />
}
<script>
$("#idForm").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var url = "~/Main/Result"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function (data) {
alert(data); // show response from the php script.
}
});
});
</script>
my controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Customer obj, string save, string cancel)
{
if (!string.IsNullOrEmpty(save))
{
ViewBag.Message = "Customer saved successfully!";
}
if (!string.IsNullOrEmpty(cancel))
{
ViewBag.Message = "The operation was cancelled!";
}
return View("Result", obj);
}
public ActionResult Result()
{
return View();
}
Not sure why the other answer was deleted, but it was 100% correct. The URL you're hitting with your AJAX is your Result action, which does nothing but return a view. You need to post to your Index action, and since the form is already set to post there, the best way to get that URL for your AJAX is to select it from the form:
var url = $('#idForm").attr("action");

ajax get boolean value from C# function T4MVC

I have a research bar on my website, the code for it is the following:
<form onsubmit="return IsValidCustomer()">
<input class=" sb-search-input" placeholder="Chercher un client..." type="text" value="" name="search" id="search">
<input class="sb-search-submit" type="submit" value="" id="submit-search">
<span class="sb-icon-search"></span>
</form>
As you see, it calls a javascript function:
function IsValidCustomer() {
var name = document.getElementById('search').value;
$.ajax({
type: 'GET',
url: lookForCustomerUrl,
data: {'name' : name },
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result);
},
error: function (e) {
alert(e.value);
}
});
return false;
}
Which will call my c# function, to see if the customer I'm looking for actually exist. If it does, for the moment, I just want to show the result, which is suppose to be True or False. But I'm only getting the error alert...
Here's my C# code, in my controller:
public virtual bool LookIfCustomerExist(string name)
{
List<Customer> customers = SearchClient(name);
bool returnedValue = customers.Count != 0;
return returnedValue;
}
The SearchClient function you see is working fine and the returned boolean is correct.
Thanks for help... I just want to save a unnecessary page...
When you make an ajax call from an aspx page to a method in the code-behind, you need to decorate the method with an attribute [Webmethod].Also, it needs to be a static method. That means, you would also need to change 'SearchClient' to a static method if it isn't so.
[Webmethod]
public static virtual bool LookIfCustomerExist(string name)
{
List<Customer> customers = SearchClient(name);
bool returnedValue = customers.Count != 0;
return returnedValue;
}

Calling a HTTP POST method in a MVC Controller from the View's Javascript & Database saving

I am trying to update a value in my database. When the user presses the update button this script is called.
View Code:
<script>
function scr_UpdateQuote(field) {
var r = confirm("Are you sure you want to update your quote?");
if (r == true) {
var textBox_UserTitle = document.getElementById(field);
*CODE TO POST METHOD HERE*
}
}
</script>
In the controller, the value is then revived and saved into the database. A message is sent back to let the user know their quote was updated.
Controller Code:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
*REPLACE QUOTE IN DATABASE*
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}
I am having difficulty finding out how to write the code described between the **'s
(For the database part I have a user-id that can be used to identify the row)
You can use form posting like this:
$("#YourForm").submit(function() {
$.post("/YourController/UpdateQuote", $("#YourForm").serialize())
//this will serialize your form into:
// newQuote=someValue&&someOtherVariable=someOtherValue etc.
.done(function(data) {
// do what ever you want with the server response
});
})
or you can use an ajax post:
$.ajax({
type: "POST",
url: "/YourController/UpdateQuote",
data: {newQuote: document.getElementById(field)},
dataType: "json",
success: function(data) {
// do what ever you want with the server response
},
error: function(){
// error handling
}
});
For using the data, assuming you have an DbContext called MyDbContext:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
// get userID somehow, either from session, or pass as another parameter here
using (var dc = new MyDbContext)
{
var quoteToUpdate = dc.QuotesTable.FirstOrDefault(q => q.UserID == userID)
quoteToUpdate.quoteColumn = newQuote;
dc.SaveChanges();
}
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}

Pass the result of AJAX callback to Partial View using JQuery

I'm using ASP.NET MVC 4. On a button click, I want to invoke ajax callback to controller method and return the data needed as Json Data. I'm able to do this using the following code:
<script>
$(document).ready(function () {
var ajax_url = '#Url.Action("GetNewItems")';
$("#submit").click(function () {
$.ajax({
url: ajax_url,
type: "POST",
datatype: "json",
success: function (data) {
debugger
}
});
});
});
[HttpPost]
public JsonResult GetNewItems()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Id = 3, Name = "c" });
items.Add(new Item() { Id = 4, Name = "d" });
return Json(items);
}
In success function, the collection of Items are returned properly. In this function, I want to call Html.Partial and pass the result as the model of the Partial view. Is this possible?
I've searched in other threads, but most of them are suggesting that Partial View is returned from Controller method and html(data) is used to render it. I'd rather not return the Partial view from Controller, as the size would have significant difference rather than returning the data only and render it manually in client-side.
So, is it possible to pass the result to Partial view in success function, or I have to manually render the elements in there?
Any help is appreciated. Thanks!
so what's the problem? just do it
[HttpPost]
public ActionResult GetNewItems()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Id = 3, Name = "c" });
items.Add(new Item() { Id = 4, Name = "d" });
return View("MypartialView",items);
}
$(document).ready(function () {
var ajax_url = '#Url.Action("GetNewItems")';
$("#submit").click(function () {
$.ajax({
url: ajax_url,
type: "POST",
success: function (data) {
$("#div").html(data);
}
});
});
});
So, is it possible to pass the result to Partial view in success
function, or I have to manually render the elements in there?
you can solve this problem in couple of way -
use AJAXFORM Post.
Alternatively you can use JQuery templates.
JQuery Templates solution
First reference following JQuery libraries -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>
Then create the template which you want to fill up with details -
<script id="personsTmpl" type="text/x-jquery-tmpl">
<tr>
<th>${Name}</th>
</tr>
</script>
As a next step define the Table in html -
<table id="tableAttendees">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tr></tr>
</table>
Have a button on the page -
<input type="button" value="Click" onclick="submitForm()" />
Finally handle the JQuery Click event of the Submit button -
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("Submit")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: "Rami" }),
success: function (data) {
$("#personsTmpl").tmpl(data).appendTo("#tableAttendees");
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
When the button is clicked, Submit Action will be hit -
public ActionResult Submit(string name)
{
return Json(new Person() { Name = name + " Its Me" });
}
which would return person object -
public class Person
{
public string Name { get; set; }
}
Now when you run the application, and click on the button, you will see the values getting appending to the table as below -
Alternatively you can use AJAX form as shown below.
AJAXFORM Solution
Say you have Index as below -
#model MVC.Controllers.Person
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#using (Ajax.BeginForm("Submit", new AjaxOptions { UpdateTargetId = "productList" }))
{
<div>
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
</div>
<div>
<input type="submit" value="Add Product" />
</div>
}
<div id='productList'>
#{ Html.RenderPartial("itsme", Model); }
</div>
Which will hit Submit action and in turn we get a partial view -
public ActionResult Submit(Person p)
{
p.Name = p.Name + " Its me";
return PartialView("itsme", p);
}
And the partial view is simple which display the name -
#model MVC.Controllers.Person
#if (Model != null)
{
#Html.LabelFor(p => p.Name, Model.Name)
}
Finally the output -
If you don't want to return Partial View then you have to use a client side code to accomplish this. There are several options. You could review jTempaltes and jQuery Templates as an options. But if you won't call more than once this Ajax I would recommend you to return Partial View.

Categories

Resources