Using Ajax to trigger an Action Result c# - c#

Using the following script:
$(document).ready(function () {
$('#submit').click(function () {
var companyId = $('#companyCoid').val();
var erpKey = $('#erpKey').val();
if (companyId == "" || erpKey == "") {
alert("You have not entered enough information");
} else {
$.ajax({
type:post,
url: '#Url.Action("ErpDocument")',
data: {
coid: companyId,
documentKey: erpKey
}
});
}
});
});
I am trying to trigger this action result which would navigate to a new view:
[HttpPost]
public ActionResult ErpDocument(string coid, string documentKey)
{
var cview = new ConnectorViewModel();
Stuff and things here....
return View(cview);
}
I am getting the information from a form above and the check for blank fields works just fine, however, the function in my controller is never hit.
EDIT: Reason it wasn't hitting the ActionResult was I had post and not "POST", this now hits my method but does not display my new view.

I think the default contenttype is xml. you may need to add this
contenttype: "application/json; charset=utf-8"
. I think that's what I've had to do before. Although unlikely, you may need to add a datatype as well.
https://api.jquery.com/jQuery.ajax/

Related

How to pass data from a controller to view during a JQuery AJAX call in MVC?

In my view, I have an AJAX call which sends an id parameter to my controller. This bit works fine. In my controller, I plan to query the database with that id, pull out associated data and want to send this back to the AJAX call/view. This is the bit I am struggling with, as I am new to AJAX calls.
var chosenSchoolID = $("#SelectedSchoolId").val();
$.ajax({
url: "/Home/GetSchoolDetailsAJAX",
type: "POST",
data: {
schoolID: chosenSchoolID
},
dataType: "text",
success: function(data) {
if (data == "success") {
}
},
error: function(data) {
if (data == "failed")
alert("An error has occured!");
}
});
The above is my AJAX call, and this does hit my controller method. However in my controller, I want to now send back other string data and I am unsure on how to do this (just placeholder code currently)
[HttpPost]
public ActionResult GetSchoolDetailsAjax(string schoolID)
{
// query database using schoolID
// now we have other data such as:
string SchoolName = "";
string SchoolAddress = "";
string SchoolCity = "";
return null;
}
Must I declare variables in my Jquery and pass into the data parameter of the AJAX call in order for the values to be passed?
Many thanks in advance
The simplest way to do this is to return the entities retrieved from your database using return Json() from your controller.
Note that when retrieving data then a GET request should be made, not a POST. In addition the default MVC configuration should have the routes setup to allow you to provide the id of the required resource in the URL. As such, try this:
$.ajax({
url: "/Home/GetSchoolDetailsAJAX/" + $("#SelectedSchoolId").val(),
type: "get",
success: function(school) {
console.log(school);
},
error: function() {
alert("An error has occured!");
}
});
[HttpGet]
public ActionResult GetSchoolDetailsAjax(string id) {
var school = _yourDatabaseContext.Schools.Single(s => s.Id == id); // assuming EF
return Json(school);
}
If you'd like to test this without the database integration, amend the following line:
var school = new {
Id = id,
Name = "Hogwarts",
Address = "Street, City, Country"
};

AJAX HTTP Method GET Goes To Server Only Once

When I make ajax request to the server with breakpoint in the action method it stops on this breakpoint only the first time. After clicking for second, third etc. it goes but never stops on this breakpoint. When I change the method from GET to POST it stops every time. What is the reason for this behaviour ?
CLIENT SIDE:
$(function () {
setListAction();
});
function setListAction() {
$("li.list").on("click", function () {
alert("active");
var id = $(this).attr("file-id");
$.ajax({
type: "GET",
url: "TechAcc/ManageFile/" + id,
beforeSend: function myfunction() {
$("#loading").css("display", "block");
$("#fade").css("display", "block");
},
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
});
});
}
SERVER SIDE:
[HttpGet]
public ActionResult ManageFile(int id = 0)
{
FileModel model = null;
if (id != 0)
model = new FileModel() { File = _repository.GetFileBy(id), GetAllFiles = _repository.GetAllFiles() };
else if (Session["Model"] != null)
model = (FileModel)Session["Model"];
else
model = new FileModel() { GetAllFiles = _repository.GetAllFiles() };
return View(model);
}
if your div with id "content" has list, it will not work.
<div id="content">
if your list is here, it won't work.
...
<li class="list">...</li>
...
</div>
if your design is like that, you need to bind click event after you replace your HTML response. i.e.,
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
//adding code here.
$("div#content").find("li.list").on("click", function() {
//same above click code should come here.
//Note: this newly added code block should not come here in click.
});
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}

Controller Action Not Found JSON and ASP.NET MVC

Hi I have this controller method
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
var data = new
{
CalculatedBMI = CalculateModel.BMICalc,
CalculatedBMIMeaning = CalculateModel.BMIMeaning
};
return Json(data, JsonRequestBehavior.AllowGet);
}
And this is my JS functions:
$('#good').click(function () {
var request = new BMICalculation();
$.ajax({
url: "CalculateAndSaveToDB",
dataType: 'json',
contentType: "application/json",
type: "POST",
data: JSON.stringify(request), //Ahhh, much better
success: function (response) {
$("#result").text(response.result);
},
});
ShowBMI();
});
function ShowBMI() {
$.ajax({
type: "GET",
dataType: "json",
contentType: "application/json",
url: "CalculateAndSaveToDB",
success: function (data) {
var div = $('#ajaxDiv');
div.html("<br/> " + "<b>" + "Your BMI Calculations: " + "</b>");
printBMI(div, data);
}
});
};
When ShowBMI() is executed, Chrome says GET http://localhost:50279/BMICalculations/CalculateAndSaveToDB/0 404 (Not Found)
The POST works as it saves to the database etc but the GET doesn't? Is there any reason for this? As you can see the URLs are exactly the same in each JS function so Im not sure why its found once nut not again the second time?
UPDATE:
After separating logic, the values appearing on the webpage are both null. See below for code changes
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
CalculateAndSaveToDB(CalculateModel.BMICalc.ToString(), CalculateModel.BMIMeaning.ToString());
return Json("", JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult CalculateAndSaveToDB(string o, string t)
{
var data = new
{
CalculatedBMI = o,
CalculatedBMIMeaning = t
};
return Json(data, JsonRequestBehavior.AllowGet);
}
That's because you've applied the [HttpPost] attribute :) That attribute renders the action available solely for POSTing and not GETing. You should move the logic that is relevant for GETing to an action with the same name but without the [HttpPost] attribute and keep the logic for handling POSTed data in the action marked with the [HttpPost] attribute.
Be advised that you should reconsider the names when separating logic into different methods, or else the names will be misleading.
Regarding your update
I would have the POST request handling action (your action marked with HttpPost) return an ActionResult which in essence would mean that the POST request handling action upon successfully handling your request would redirect the user to a confirmation page or somewhere else. Wherever's preferable really :)
Try to approach it logically, what would be the natural chain of events upon POSTing the data? What would you as a user expect to happen?
Regarding your GET action, that is because you are not sending in the parameters o and t, which you then immediately return. Since nothing happens to these parameters in your logic and they are not otherwise specified, they will contain null which is the default value for variables of type string. Are you not intending to retrieve data from the database, rather than supply two parameters only to immediately return them?

Searching in asp.net mvc4

I am newbie to asp.net MVC4.
For searching names from list i tried a search filter in MVC4.
This is controller-
public ActionResult SearchUser(string Email, int? UserId) {
var system = from u in db.SystemUsers
select u;
if (!String.IsNullOrEmpty(Email)) {
system = system.Where(c => c.Email.Contains(Email));
}
return View(system.Where(x=>x.Email==Email));
}
View-
<input type="text" id="search-User" />
<button id="text-email">search</button>
Ajax handling-
<script type="text/javascript">
$(document).ready(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
alert(areavalue);
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json'
});
});
});
</script>
ViewModel-
public class UserModel
{
[Required]
public string Email { get; set; }
public int UserId { get; set; }
}
I have many users as a list, so i wanted to filter out any user from the list. For this I am using input element to get exact name as it is in list. Thus this name is passed to controller to find the exact match.
It is showing value i passed through ajax handling but not showing filtered result.
How can I perform searching in Asp.net MVC4?
I would use better Load() function for this porpose:
<script>
$(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
$(".YourDivForResults").Load('/Allusers/SearchUser/?Email=' + areavalue)
});
});
</script>
And, as a recommendation, modify a bit your ActionResult as follows:
system = system.Where(c => c.Email.ToUpper().Trim().Contains(Email.ToUpper().Trim()));
This way you will avoid problems with empty spaces and Upper or Low letters.
Your ajax function is sending the data up to the server, but it is not doing anything with the result. In order to use the results, you should use the done promise method in the jQuery .ajax method that you are calling. It will look something like this:
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json'
}).done(
function(data, textStatus, jqXHR) {
var object = jQuery.parseJSON(data);
// LOGIC FOR UPDATING UI WITH RESULTS GOES HERE
}
);
You could alternatively use the Success callback option (instead of done). But the key is to provide logic for what to do with the data returned by the Action.
Also, if you are intending to return results using your ViewModel, you may need to return UserModel objects from your Linq query.
And if you are expecting JSON back from your action, you should not return View. Instead, try returnins JSON(data). (See here for more).
You need to make small change to you action like,
public ActionResult SearchUser(string Email, int? UserId) {
var system = from u in db.SystemUsers
select u;
if (!String.IsNullOrEmpty(Email)) {
system = system.Where(c => c.Email.Contains(Email));
}
return Json(system.Where(x=>x.Email==Email),JsonRequestBehavior.AllowGet);
}
and in your ajax call
$(document).ready(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
alert(areavalue);
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json',
success:function(data){JSON.stringify(data);}
});
});
});
so that you will get the search result in a json format. you can make use of it. Hope it helps

Passing a parameter from JavaScript to a controller

I am trying to pass a string value to a create item dialog, and am not sure on how to do it.
This is the code in my view:
JavaScript:
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}
View:
<td>#route</td>
<td>
Add
</td>
Controller:
public ActionResult Create(string routeName = "")
{
PopulateRouteInfoViewBag();
var newRoute = new RouteInformation();
newRoute.Name = routeName;
return View(newRoute);
}
I'm trying to take the value in #route and pass it over to the Create controller to have my dialog pop up with the passed in string value.
Use the ActionLink html helper method and pass the route variable like this.
#{
string route="somevaluehere";
}
#Html.ActionLink("Add","Create","YourControllerName",
new { routeName=route},new {#id="addLnk"})
Now handle the click event
$(function(){
$("#addLnk").click(function(e){
e.preventDefault(); //prevent normal link click behaviour
var _this=$(this);
//do your ajax call now
$.ajax({
url: _this.attr("href"),
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = 'someValidUrlHere'
else
$.facybox(data);
}
});
});
});
Also, You may consider building the path to the new page(action method) and return that as part of your JSON result and let the client read it from the JSON.
instead of appending the route variable value to the querystring, you may consider it as the part of message body.
There are two options. 1, use Url.Action("controllerName", "actionName", new {routeName = "your route name here"}) or 2, use the data property of the object passed into $.ajax.
For 2 your javascript would look something like
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
data: {
route: "your data here"
}
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}

Categories

Resources