What I want to do is call an alert dialog box from within the controller.
The reasoning is because the controller is called by the view via an ajax call and does not reload the page thus would not be able to compare any new data in a tempdata or otherwise.
The purpose of the action is to check if the student checking into the class is supposed to be there or not. If the class is not in their schedule then the permission bool remains false and an alert should pop up stating that the student is not in the class.
public ActionResult Action(string ccod, int sid)
{
IEnumerable<MvcStudentTracker.Databases.Course> result = from course in db.Courses
join sched in db.Schedules on course.CourseCode equals sched.ClassCode
where sched.StuID == sid
select course;
bool permission = false;
foreach (var item in result)
{
if (item.CourseCode == ccod)
permission = true;
}
if (permission == false)
{
//call alert dialog box "This student is not signed up for this class"
}
return null;
}
Let's change your action so it returns a JsonResult object. This way we can easily manipulate its results on the client side. As you are already calling it using javascript, that's the best solution.
So, your action:
public JsonResult Action(string ccod, int sid)
{
IEnumerable<MvcStudentTracker.Databases.Course> result = from course in db.Courses
join sched in db.Schedules on course.CourseCode equals sched.ClassCode
where sched.StuID == sid
select course;
return Json(result.Any(x => x.CourseCode == ccod), JsonRequestBehavior.AllowGet);
}
And your view:
$.ajax({
url: 'root/Action',
cache: false,
type: 'GET',
data: {
ccod: $('...').val()
, sid: $('...').val()
},
dataType: 'json'
}).done(function (data) {
if (data) {
//ok!
}
else {
//permission denied
}
});
Note that I've changed your action code. You may want to review it and change it a little more.
add this to your code :
Page.ClientScript.RegisterStartupScript(Page.GetType(), "alrt", "alert('Anything');", true);
like htis
public ActionResult Action(string ccod, int sid)
{
IEnumerable<MvcStudentTracker.Databases.Course> result = from course in db.Courses
join sched in db.Schedules on course.CourseCode equals sched.ClassCode
where sched.StuID == sid
select course;
bool permission = false;
foreach (var item in result)
{
if (item.CourseCode == ccod)
permission = true;
}
if (permission == false)
{
//call alert dialog box "This student is not signed up for this class"
Page.ClientScript.RegisterStartupScript(Page.GetType(), "alrt", "alert('This student is not signed up for this class');", true);
}
return null;
}
Related
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"
};
Im doing a college project with entity framework and i'm doing some JOIN's. I was doing well until I got to this JOIN that I don't know how to do.
Simplifying the functionality I have to implement: I have a button and when I click on it, it must show all the information from the tables, that's why I need to make the JOIN's, and I created a model for this purpose.
This is a screenshot of my SQL database:
SQL Database
And this is the code where I need to make the MetaEspecifica JOIN where the
foreign key is from AreaProcesso :
// GET: AreaProcesso/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var item = (from ap in db.AreaProcesso
join mg in db.MetaGenerica on ap.IdAreaProcesso equals mg.IdMetaGenerica
join model in db.Modelo on ap.IdAreaProcesso equals model.IdModelo
from nc in db.NivelCapacidade
from c in db.Categoria
from me in db.MetaEspecifica
where ap.IdAreaProcesso == id.Value
select new AreaProcessoModelView()
{
SiglaMetaGenerica = mg.Sigla,
NomeMetaGenerica = mg.Nome,
DescricaoMetaGenerica = mg.Descricao,
Sigla = ap.Sigla,
Nome = ap.Nome,
Descricao = ap.Descricao,
SiglaModelo = model.Sigla,
NomeModelo = model.Nome,
DescricaoModelo = model.Descricao,
SiglaNivelCapacidade = nc.Sigla,
NomeNivelCapacidade = nc.Nome,
DescricaoNivelCapacidade = nc.Descricao,
NomeCategoria = c.Nome
}).FirstOrDefault();
if (item == null)
{
return HttpNotFound(); // Or a return a view with message "item not found"
}
return View(item);
}
If you need have HTML page with JSON use this section under view page
#section Scripts {
var jsonData= #Html.Raw(Json.Encode(Model.YourDataCollection));
}
If you only need JSON data in the browser, change your controller and return Json like this:
return Json(item, JsonRequestBehavior.AllowGet);
Be careful if use return Json you say MVC this is not view page and only data serialization page
To view Details.cshtml file does not need a model, only after the design page layout only add this script in the script section
#section Scripts {
$.ajax({
dataType: 'json',
url: '#Url.Action("Details")',
type: 'GET',
cache: false,
success: function(result) {
// use json result
}
});
}
I want to get the particular insurance for the particular client. When I got to the url {clientId}/insurances/{insuranceId} with this code below. I end up getting 404 error. How may I able to solve it? Am I using correct method?
[HttpGet("{clientId}/insurances/{insuranceId}")]
public IActionResult Get(int clientId, int insuranceId)
{
var insurances = context.PatientIntakeInsurances.SingleOrDefault(i => i.insurance_id == insuranceId);
if (insurances == null)
return HttpNotFound();
return new ObjectResult(insurances);
}
**Here is my javascript code
state("clients.detail.insurances.detail", {
url: "/{insuranceId:[0-9]{1,10}}",
templateUrl: "clients/clients.detail.insurances.detail.html",
controller: ("$scope", "$log", "clientsService", "$stateParams",
function ($scope, $log, clientsService, $stateParams)
{
clientsService.getInsurance($stateParams.clientId,$stateParams.insuranceId,
function (insurances)
{
$scope.insurances = insurances;
})
}
**Here is my service
getInsurance: function(clientId, insuranceId, callback){
$http({
method: "GET",
url: "/api/clients/" +clientId +"/insurances/" + insuranceId
// url: "/api/insurances/" + id
}).then(function(response){
if(typeof callback === "function")
callback(response.date);
}, function(response){
});
},
Currently on the I have some inline javascript, which makes an ajax call to a partial view controller which should have updated the viewbag along with it. However this does not seem to be the case, the data seems to persist from the main view which is null because it was never set there and if it was set then the data would still persist(tested).
Here is my javascript ajax call.
$.ajax({
url: btn.data('action-url'),
data: {
id: btn.data('id')
},
type: 'GET',
success: function (data) {
//delete all panels before showing new ones
$('.panel.panel-default').remove();
//push the new panels into the view
//$('#dash-content').html(data);
//Construct the partial view to be input into the main view
//Checks to see if browser supports templates
if ('content' in document.createElement('template')) {
var widgetModel = #Html.Raw(Json.Encode(ViewBag.widgets));
for (var i = 0; i < widgetModel.length; i++) {
var clone = loadwidgets(widgetModel[i]); //This function is in an external js file
var inputDestination = document.querySelector('#col2');
inputDestination.appendChild(clone);
console.log(inputDestination);
}
}
and here is the Action that it is calling.
public ActionResult Dashboard(int? id)
{
ModelState.Clear();
//get all widgets associated dashboard
var getWidgetsQuery = (from widgets in db.widgets
where widgets.DashID == id
select widgets);
ViewBag.widgets = getWidgetsQuery.ToList();
return PartialView();
}
Add an action to return the data i.e.
public ActionResult DashboardJson(int? id)
{
//get all widgets associated dashboard
var getWidgetsQuery = (from widgets in db.widgets
where widgets.DashID == id
select widgets);
var widgets = getWidgetsQuery;
return Json(widgets, JsonRequestBehavior.AllowGet);
}
Declare and serialize your model above the json call as you have done:
var widgetModel = #Html.Raw(Json.Encode(ViewBag.widgets));
Then within your success call simply re-assign it to the returned data:
widgetModel = data;
I am using knockout and using my custom function given below to make ajax call to controller. if any unhandlled exception occurs it returns entire page as response which results on reponse displaying entire html of page please suggest proper way of handling this
function asyncComputed(evaluator, owner) {
var result = ko.observable(), currentDeferred;
result.inProgress = ko.observable(false); // Track whether we're waiting for a result
ko.computed(function () {
// Abort any in-flight evaluation to ensure we only notify with the latest value
if (currentDeferred) { currentDeferred.reject(); }
var evaluatorResult = evaluator.call(owner);
// Cope with both asynchronous and synchronous values
if (evaluatorResult && (typeof evaluatorResult.done == "function")) { // Async
result.inProgress(true);
currentDeferred = $.Deferred().done(function (data) {
result.inProgress(false);
if (data.hasOwnProperty("HasFailed") == true && data.ErrorCode == 1)//For Session Time Out
{
$("#timeoutmessage")
.html('<div class="modal-backdrop">' +
'<div style="color:white;" class="middle">' +
'<div class="row-fluid"><div>Your session has timed out, please Login here again.</div></div>' +
'</div>')
.show();
}
result(data);
});
evaluatorResult.done(currentDeferred.resolve);
} else // Sync
result(evaluatorResult);
});
return result;
}
and my calling function is
self.currentRevenue = asyncComputed(function () {
self.currentRevenueinProgress(true);
var duration = self.duration();
var location = self.location();
return $.ajax({
url: getCurrentTotalRevenue,
type: "GET",
data: { "durationType": duration, "storeId": location }
}).done(function (result) {
self.currentRevenueinProgress(false);
if (result.hasOwnProperty("HasFailed") == true) {
self.currentRevenueError(true);
}else{alert('success');}
});
i am using asycComputed function for making ajax calls if any of the ajax call thows exception all of the ajax call fails and result html of the page in response.
Can i use filters here Please suggest
You could write a custom action filter on the server which catches the exceptions and changes them into JSON responses.
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
Then you just have to add the custom attribute to your controller action.