How to use ajax in asp.net MVC - asp.net-mvc-3

How can I return a class object from Ajax in asp.net MVC....???
Example:
Ajax call from html:
$.ajax({
type: 'POST',
url: '/Tutorial/Web/AlignmentRule/GetAlignmentDetails',
data: { alignmentRuleId: alignmentRuleId },
success:
function (data) {
alert(data.Id);
alert(data.alignmentData.Id);
$("#ruleName").val(data.alignmentData.Name);
$("#level").val(data.alignmentData.Id);
},
error:
function () {
alert("Server Error!!!!");
},
dataType: 'JSON',
async: false
});
and Action method in contorller is:
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData );
}
And I want to return a list of alignmentRule class objects also....

you can compose your return object as you want, for example, create a ViewModel as decorator to hold everything you want to pass, like:
var json = new JsonViewModel() {
alignmentData = alignmentData,
rules = yourRules
};
return Json(json);

The error is thrown because by default MVC framework does't allow you to respond to an HTTP GET request with a JSON (because of security reasons).
In order to make it work, when you retrurn Json in your action, you need to specify JsonRequestBehavior.AllowGet
[HttpPost]
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData, JsonRequestBehavior.AllowGet);
}
EDIT
Annotate your action with [HttpPost] attribute.
For further investigation on this topic check this article

Related

jQuery Ajax returns undefined result from asp.net core controller's POST action

Can't make friends out of my AJAX and MVC 6 controller.
This is how I define AJAX call for SetFormValues POST-action:
Index.cshtml
$.ajax({
type: "Post",
url: "Home/SetFormValues",
data: { Name: name, Phone: phone },
dataType: "json",
success: function (result) {
SuccessFunction(result)
},
error: function () {
alert("ALARM!");
},
async: false
})
I see that the controller works and executes SetFormValues action which is defined as the following:
HomeController.cs
[HttpPost]
public JsonResult SetFormValues(string Name, string Phone)
{
string NameErrorStr = string.IsNullOrWhiteSpace(Name) ? "Обязательное поле" : string.Empty;
string PhoneErrorStr = string.IsNullOrWhiteSpace(Phone) ? "Обязательное поле" : string.Empty;
var result = new { NameError = NameErrorStr, PhoneError = PhoneErrorStr };
var jresult = Json(result);
return jresult;
}
Debugger shows that action executes and my resulting JSON object fills correctly:
Finally, his is how SuccessFunction(result) is defined:
Index.cshtml again
function SuccessFunction(result) {
alert("Success function shit executed. result=" +
result + "NameError=" +
result.NameError + ". PhoneError=" +
result.PhoneError);
$("#nameerror").append(result.NameError);
$("#phoneerror").append(result.PhoneError);
}
Function works, alert is raised but result stay 'undefined' no matter what I do:
result = [object Object]
result.val = undefined
Maybe I have to deserialize JSON result properly or fill some properties in it's declaration above, I don't know.
I'm using the lattest libraries for jquery, validate and unobtrusive.
I also tried JSON.parse(result), as it mentioned in the lattest jQuery specification, but it didn't work as well.
Please, help me :)
In asp.net core, by default, the serializer uses camelCase property names for json serialization. So your result will be like this
{"nameError":"some message","phoneError":"some message here"}
Javascript is case sensitive. So use the correct case
$("#nameerror").append(result.nameError);
$("#phoneerror").append(result.phoneError);
For reference : MVC now serializes JSON with camel case names by default
its working perfectly when i have added this line in startup file
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddDbContext<DataContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DbCrudOperation")));
}
function Edit(id) {
$.ajax({
type: 'GET',
url: "/AjacCrud/EditPahe/" + id,
dataType: 'JSON',
contentType: "application/json",
success: function (response) {
$("#nameEmp").val(response.ID);
console.log(response.ID);
},
error: function (GetError) {
alert(GetError.responseText);
}
});
};

Using AJAX with MVC 5 and Umbraco

I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.
FYI, I am using MVC 5 and Umbraco 7.
I currently have the ajax code within the partial view (will want to move this to a js file at some point).
Here is the ajax code:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '#Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
Here is the Controller:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
The above code gives me a 404 Not Found Error:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
If I use:
url: '#Url.Action("GetTimeDifference", "TimeDifference")'
The #Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.
I have also tried:
#Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url is still Null.
I have added entries in to the Global.asax.cs for routing i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This doesn't seem to do anything.
I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.
As I am new to this I'm sure it something very simple I am missing.
Many thanks,
HH
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.
Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.

Ajax not returning desired results or not working at all

I have been trying to load return a JsonResults action from a controller in MVC using ajax call. I can see that the alert() function is triggering well but the ajax is not executing. I have search for several sources but to no avail.
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.Where(l3 => l3.LevelTwoItem_ID == selectedID);
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
The below too is the javascript calling for the json method.
<script>
function FillBussLicence_L3items() {
alert("You have clicked me");
var bl2_Id = $('#BussLicenceL2_ID').val();
//alert(document.getElementById("BussLicenceL2_ID").value);
alert(bl2_Id);
$.ajax({
url: 'StartSurvey/FillBusinessLicenceL3/' + bl2_Id,
type: "GET",
dataType: "JSON",
data: "{}", // { selectedID : bl2_Id },
//contentType: 'application/json; charset=utf-8',
success: function (bussLicence_L3items) {
$("#BussLicenceL3_ID").html(""); // clear before appending new list
$.each(bussLicence_L3items, function (i, licenceL3) {
$("#BussLicenceL3_ID").append(
$('<option></option>').val(licenceL3.LevelThreeItem_ID).html(licenceL3.LevelThreeItem_Name));
});
}
});
}
Also, I have tried this one too but no execution notice.
Thanks a lot for your help in advance.
After looking through the browser's console, I noticed that the LINQ query was tracking the database and was creating a circular reference so I changed the query to the following and voila!!
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.
Where(k => k.LevelTwoItem_ID == selectedID).
Select(s => new { LevelThreeItem_ID = s.LevelThreeItem_ID, LevelThreeItem_Name = s.LevelThreeItem_Name });
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
There was nothing wrong with the ajax call to the controller.

How I can pass FormCollection object with $.ajax(...)

I am working C# MVC application and I have 2 action method in a controller:
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult SaveBasicInformation(FormCollection collection)
{.....}
[MultipleButton(Name = "action", Argument = "Submit")]
public ActionResult SubmitRequest(FormCollection collection)
{....}
The above code is working fine without ajax request. Now my question is how i can to pass "FormCollection" in $.ajax(..) for specific controller method.
var input = $(':input');
$.ajax({
url: '#Url.Action("SaveBasicInformation", "Home")',
type: 'POST',
cache: false,
data: input,
success: function (data) {
alert("Success");
},
error: function (result) {
alert("Error");
alert(result.responseText);
}
});
Here is the error message when i use the above ajax code:
The current request for action 'SaveBasicInformatio'' on controller type HomeController'
is ambiguous between the following action methods: System.Web.MVC.Action Result
SubmitRrquest(System.Web.formCollection)....
Thank you for your help...
The `[MultipleButton]' attribute is a custom attribute possibly from this SO answer? which may be causing the problem as its an ajax call. Try removing the attributes.

Multiple AJAX requests in MVC3 application

The situation, I'm making multiple ajax/json requests on the same page to a controller, which returns a JsonResult.
I know this is a problem with the session state, I've added the [SessionState(SessionStateBehavior.Disabled)] attribute on my controller class, but nothing seems to work, my second ajax request just wont get the return data.
the controller:
[SessionState(SessionStateBehavior.Disabled)]
public class IndexController : Controller
{}
the two json methods:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetLatestListJSON()
{
Thread.Sleep(5000);
ArticleRepository repo = new ArticleRepository();
IList<ArticleModel> list = repo.GetLatestContent(10);
return Json(list, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCustomerJSON()
{
Thread.Sleep(5000);
CustomerRepository Repo = new CustomerRepository();
IList<Customer> cust= Repo.GetCustomer();
return Json(cust, JsonRequestBehavior.AllowGet);
}
The second ajax call, the other one is very similar, I never get to see the 'succes'-alert.
<script type="text/javascript">
$(document).ready(function () {
alert('before');
$.getJSON("/Index/GetCustomerJSON", null, function (data) {
alert('succes');
$("#loadingGifVideo").hide();
$.each(data, function (index, mod) {
});
});
});
Thanks guys :)
If you put a break-point in your GetCustomerJSON method and run this in Visual Studio does the method ever get called? It does
EDIT
Try switching from getJSON to the ajax method so you can capture any errors. Like so:
$.ajax({
url: "/Index/GetCustomerJSON",
dataType: 'json',
data: null,
success: function (data) { alert('success'); }
error: function (data) { alert('error'); }
});
Do you get an "error" alert?

Resources