Call MVC Controller from AngularJS using JSON in ASP.Net MVC - c#

JsonResult method not calling through $http call,
I am working on a project that uses ASP.NET MVC, AngularJS I am calling a mvc controller from AngularJS. I am getting an jsonresult as in the call to a MVC controller from AngularJS .
this is the result
[
{
"Branch_ID": 1,
"Branch_Name": "sdsds",
"Branch_Address": "sfsdfsdf",
"Branch_email": "sdfsdfsdf",
"Branch_Notes": "sfsffsfd",
"Branch_Manager": null,
"Branch_Phone": null,
"Branch_TimeFrom": "/Date(-2208996000000)/",
"Branch_TimeTo": "/Date(-2208996000000)/",
"saturday": false,
"sunday": false,
"monday": false,
"tuesday": false,
"wednesday": false,
"thursday": false,
"friday": false,
"Departments": null
}
]
branches controller
public class BranchesController : Controller
{
private IRepositoryBase<Branches> BrancheRepository;
public BranchesController(IRepositoryBase<Branches> brancheRepository)
{
this.BrancheRepository = brancheRepository;
}
// GET: Branches
public JsonResult Index()
{
var branches = BrancheRepository.GetAll();
//if (!String.IsNullOrEmpty(searchString))
//{
// branches = branches.Where(s => s.Branch_Name.ToUpper().Contains(searchString.ToUpper()));
//}
return Json(branches, JsonRequestBehavior.AllowGet);
}
}
Index.cshtml
<div class="container" ng-controller="branch-controller">
<div class="panel panel-info">
<div class="panel-heading">
Branch Details - Grid CRUD operations
</div>
<table class="table table-bordered">
<thead style="background-color:lightblue;">
<tr>
<th> Branch Address</th>
<th> Branch Email</th>
<th>Branch Name</th>
<th>Branch Notes</th>
<th> Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="branche in Branches">
<td>{{branche.Branch_ID}}</td>
<td>{{branche.Branch_Address}}</td>
<td>{{branche.Branch_email}}</td>
<td>{{branche.Branch_Name}}</td>
<td>{{branche.Branch_Notes}}</td>
<td style="width:200px;">
Update
Delete
</td>
</tr>
</tbody>
</table>
</div>
Module.js
var myapp;
(function () {
myapp = angular.module('my-branches', []);
})();
Controller.js
myapp.controller('branch-controller', function ($scope, branchService) {
//Loads all branch records when page loads
loadBranches();
function loadBranches() {
var BrancheRecords = branchService.getAllBranches();
BrancheRecords.then(function (data) {
//success
$scope.Branches = data;
},
function (error) {
console.log(error);
alert("Error occured while fetching branche list...");
});
}
});
Service.js
myapp.service('branchService', function ($http) {
this.getAllBranches = function () {
return $http.get("/Branches/Index").then(function (response) {
return response.data;
});
};
});

First of all you need to change you code as it is shown in #georgeawg's answer and then your remaining problem is that you are using invalid property names. The result should look like this
<td>{{branche.Branch_Address}}</td>
<td>{{branche.Branch_email}}</td>
<td>{{branche.Branch_Name}}</td>
<td>{{branche.Branch_Notes}}</td>

Change the service call to:
var BrancheRecords = branchService.getAllBranches();
BrancheRecords.then(function (data) {
//success
$scope.Branches = data;
},
function (error) {
console.log(error);
alert("Error occured while fetching branche list...");
});
Change the service to:
myapp.service('branchService', function ($http) {
this.getAllBranches = function () {
return $http.get("Branches/Index").then(function(response) {
return response.data;
});
};
});
The data is assigned to the data property of the response object.
For more information, see
AngularJS $http Service API Reference - returns

Related

Angular.js routing for views in ASP.net MVC app not working

I'm new to web development and I'm currently trying to separate my UI by keeping my UI in Angular.js using views and routing and controllers and services. Whereas, I'm using a Web API to fetch the data from the database.
I'm trying to figure out how to get the views to work using Angular.js instead of using Asp.net's razor MVC. It works fine if I use the default routing from the ASP.net MVC web app and api but won't work if I use Angular.js routing.
I've separated my Views in a folder and created the views I want
I have set up a module with the routing for the separate views as well as the controller associated with them.
I have included the app as ng-app directive in the html file.
Index.cshtml:
<div ng-app="myApp">
<div ng-controller="StudentCtrl">
<tbody>
<tr ng-repeat="dataModel in students">
<td style="display:none">{{dataModel.StudentID}}</td>
<td> {{dataModel.FirstName}}</td>
<td> {{dataModel.LastName}}</td>
<td>{{dataModel.Email}}</td>
<td>{{dataModel.Address}}</td>
<td style="text-align:right; color:white">
<span>
<span id="save" class="btn btn-primary margin-right-btn"
ng-click="GetStudentByID(dataModel)">
Edit
</span>
</span>
</td>
<td style="text-align:right; color:white">
<span>
<span id="save" class="btn btn-danger margin-right-btn"
ng-click="DeleteStudent(dataModel)">
Delete
</span>
</span>
</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/ScriptsNg/Module/sepView.js"></script>
<script src="~/ScriptsNg/Controller/StudentCtrl.js"></script>
<script src="~/ScriptsNg/Service/CrudService.js"></script>
Controller in Angular.js: (StudentCtrl.js):
sepView.controller('StudentCtrl', ['$scope', 'CrudService',
function ($scope, CrudService) {
// Base Url
var baseUrl = '/api/StudentAPI/';
$scope.btnText = "Save";
$scope.studentID = 0;
$scope.SaveUpdate = function () {
var student = {
FirstName: $scope.firstName,
LastName: $scope.lasttName,
Email: $scope.email,
Address: $scope.address,
StudentID: $scope.studentID
}
if ($scope.btnText == "Save") {
var apiRoute = baseUrl + 'SaveStudent/';
var saveStudent = CrudService.post(apiRoute, student);
//Callback to check what kind of response we received:
saveStudent.then(function (response) {
if (response.data != "") {
alert("Data Saved Successfully");
$scope.GetStudents();
$scope.Clear();
} else {
alert("Some error");
}
}, function (error) {
console.log("Error: " + error);
});
}
else {
var apiRoute = baseUrl + 'UpdateStudent/';
var UpdateStudent = CrudService.put(apiRoute, student);
UpdateStudent.then(function (response) {
if (response.data != "") {
alert("Data Updated Successfully");
$scope.GetStudents();
$scope.Clear();
} else {
alert("Some error");
}
}, function (error) {
console.log("Error: " + error);
});
}
}
app module (sepView.js):
var sepView = angular.module('myApp', ['ngRoute']);
sepView.config(function
($routeProvider) {
$routeProvider
.when('/', {
controller:
'StudentCtrl',
templateUrl:
'Views/Student/Index.html'
})
.otherwise({
redirectTo: '/'
});
});
Service to retrieve data from Api:
sepView.service('CrudService', function ($http) {
var urlGet = '';
this.post = function (apiRoute, Model) {
var request = $http({
method: "post",
url: apiRoute,
data: Model
});
return request;
}
this.put = function (apiRoute, Model) {
var request = $http({
method: "put",
url: apiRoute,
data: Model
});
return request;
}
This is what the MVC generated controller looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CRUDOperations.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
return View();
}
public ActionResult viewAllStudents() {
return View();
}
}
}
This is what is happening:
https://imgur.com/a/nOsilNh
As you can see, angular can't access what it needs to populate the view. It was working fine when I was using Razor pages and MVC default routing.

Jquery DataTables serverside in .net core

I am trying to use jQuery DataTables server-side with .net core.
I am using Ajax to call my controller and I have strongly typed View with a table without body.
I am getting data in my controller but it seems I can't display it.
I thought it was JSON (https://dotnetcoretutorials.com/2018/05/05/setting-json-serialization-configuration-at-runtime-on-a-net-core-api/) but I checked and it seems it wasn't.
I tried with this tutorial but still can't find what I am doing wrong.
I just can display the "sDefaultContent" defined in Ajax.
Controller:
[HttpPost]
public async Task<IActionResult> LoadTransaction()
{
var requestFormData = Request.Form;
List<Transactions> data = await ApiClientFactory.Instance.GetInvoice();
dataList = data;
try
{
var listData = ProcessModuleCollection(data, requestFormData);
dynamic response = new
{
Data = listData,
Draw = requestFormData["draw"],
RecordsFiltered = data.Count,
RecordsTotal = data.Count
};
return Ok(response);
//return Json(response);
}
}
View:
<div class="row">
<div>
<div >
</div>
<div class="panel-body">
<table id="example" class="table table-striped table-hover responsive">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.ValueDate)
</th>
<th>
#Html.DisplayNameFor(model => model.StructuredMessage)
</th>
</tr>
</thead>
</table>
</div>
</div>
(function($) {
var generateCustomerTable = $("#example")
.dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/LoadTransaction",
"method": "POST"
},
"columns": [
{ "data": "ValueDate", "name": "ValueDate", "sDefaultContent": '0-0-0000', "autoWidth": true },
{ "data": "StructuredMessage", "name": "StructuredMessage", "sDefaultContent": '0-0-0000', "autoWidth": true },
],
"ordering": true,
"paging": true,
"pagingType": "full_numbers",
"pageLength": 10
});
})(jQuery);
here is the printScreen of my console
console PrintScreen
i must admit as often the community StackOverFlow had already the answer
the thing missing is in the ajax call datasrc
this post helps me understanding what i was trying to do
and reading a bit more comments
'dataFilter': function(data){
var json = jQuery.parseJSON( data );
json.RecordsTotal = json.total;
json.RecordsFiltered = json.total;
json.Data = json.list;
return JSON.stringify( json ); // return JSON string
}
in this particular case regarding what i am sending from my controller

The view 'GetMetaDataDetails' or its master was not found or no view engine supports the searched locations

I have a page lets say Edit.cshtml in that page is a dropdownlist of item to updated. the loading of that page has no problem, the problem comes when I select an item on the dropdownlist and execute an ajax call.
$('#dDL').kendoDropDownList({
optionLabel: "Select",
dataTextField: "Value",
dataValueField: "Id",
dataSource: {
transport: {
read: '#Url.Action("GetItems", "BulkEdit")',
}
},
change: function (e) {
//this is where i call the '#Url.Action("GetMetaDataDetails", "BulkEdit")'
var test = getMetaDataDetails();
popupwindow.data("kendoWindow").open();
popupwindow.kendoWindow({
width: "600px",
title: "Mapping",
visible: false,
//modal: true,
animation: {
close: {
effects: "fade:out"
}
},
actions: [
"Pin",
"Minimize",
"Maximize",
"Close"
],
}).data("kendoWindow").center().open();
}
});
it goes through the controller with no issue, but it throws error if I return a view. Why?
this is my ajax call:
function getMetaDataDetails() {
return $.ajax({
type: "POST",
url: '#Url.Action("GetMetaDataDetails", "BulkEdit")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ itemTypeID: itemtypeID.toString() }),
dataType: "json",
success: function (data) {
debugger;
var checks = data;
},
error: function (data) {
debugger;
var check = data;
alert(result);
}
});
}
and this is my controller:
[HttpPost]
public virtual ActionResult GetMetaDataDetails(int itemTypeID)
{
var importProperties = GetImportColumnProperties(GetModel(itemTypeID));
var result = JsonConvert.SerializeObject(importProperties, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
ViewData["MetaDataModel"] = importProperties;
return Json(result, JsonRequestBehavior.AllowGet);
}
This is the pop-up window that should be populated after executing the getMetaDataDetails(), itemMetaData should have the values return by getMetaDataDetails()
#(Html.Kendo().Window()
.Name("itemwindow")
.Title("Item Mapping")
//.Modal(true)
.Content(#<text>
<table class="table table-bordered">
<thead>
<tr>
<th>Table Column</th>
<th>Excel Column</th>
</tr>
</thead>
#foreach (var props in itemMetadata.GetType().GetProperties())
{
var label = props.GetCustomAttribute<CanBulkUpdateAttribute>().CanBulkUpdate;
if (label == true)
{
var disp = props.GetCustomAttributes<DisplayPropertyName>();
<tbody>
<tr>
<td class="col-sm-3">
<label>
#disp.First().DisplayName
</label>
</td>
<td class="col-sm-3">
<select kendoDropDownList name="" id="ddlitem_#props.Name" style="width :250px;"></select><br>
</td>
</tr>
</tbody>
}
}
</table>
<button id="uploadAll" onclick="updatetable()" class="btn btn-primary">Update</button>
</text>)
//.Width(420)
.Height(440)
.Visible(false)
)
I need to use the return of GetMetadataDetails as model for my "popupwindow"
Hope you can help me.

jQuery AJAX, conditional not working

My function makes a search by ID and by name, and I'm doing it in MVC. The problem is that it enters the conditional (if) and the AJAX is run correctly, but then it also goes to the else and runs it too. Apparently my data in the dialog is blank because it send the alert window. It sometimes opens the dialog correctly, but when I change the module and come back the if and else are run again and the blank dialog appears.
What can be happening? When I make the first click, it blocks, I click again and then the data appears...
function buscaProducto(url, cod, name) {
if (cod.length != 0 || name.length != 0) {
var producto = name;
var identidad = cod;
$.ajax({
url: url,
type: "POST",
dataType: "html",
error: AjaxFailure,
beforeSend: AjaxBegin,
data: { productoNombre: producto, identidad: identidad },
success: function (data) {
$("#dialog").dialog({
bigframe: true,
modal: true,
autoOpen: true,
width: 900,
heigth: 700,
resizable: false,
});
$("#progressbar").hide();
$("#dialog").html(data);
console.log("Entregó los datos al #dialog");
}
});
}
else {
alert("<p>Debe ingresar una opcion de busqueda</p>", $(window).height() / 3)
this.abort();
}
}
I think the cache might be stuck
the controller
[HttpPost]
public ActionResult BusquedaProducto(string productoNombre, string identidad)
{
if (productoNombre.Equals(""))
{
if (identidad.Equals(""))
{
return HttpNotFound();
}
else
{
var code = (from p in db.GN_Portafolio
where p.CodigoPortafolio.StartsWith(identidad) && p.SenSerial == true
select p).ToList();
if (code.Equals("0"))
{
return HttpNotFound();
}
else
{
return View(code);
}
}
}
else
{
var producto = (from p in db.GN_Portafolio
where p.NombrePortafolio.StartsWith(productoNombre)
select p).ToList().Take(100);
if (producto.Equals("0"))
{
return HttpNotFound();
}
else
{
return View(producto);
}
}
}
the view
#model IEnumerable<SifActivoFijo.Models.GN_Portafolio>
<form class="items">
<label>items por Pagina: </label>
<select>
<option>5</option>
<option>10</option>
<option>15</option>
</select>
</form>
<input name="button" type="button" onclick="$('#dialog').dialog('close');" value="Cerrar" />
<table class="tablas">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.CodigoPortafolio)
</th>
<th>
#Html.DisplayNameFor(model => model.NombrePortafolio)
</th>
<th></th>
</tr>
</thead>
<tbody id="pagina">
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CodigoPortafolio)
</td>
<td>
#Html.DisplayFor(modelItem => item.NombrePortafolio)
</td>
<td>
<input class="seleccion" type="button" value="Seleccionar" />
</td>
</tr>
}
</tbody>
</table>
<div class="holder"></div>
<script type="text/javascript">
$(document).ready(function () {
$('input.seleccion').click(function () {
var codigo = $(this).parent().prev().prev();
var nombre = $(this).parent().prev();
$('#activoFijo_GN_Portafolio_CodigoPortafolio').val($.trim(codigo.text()));
$('#GN_Portafolio_CodigoPortafolio').val($.trim(codigo.text()));
$('#nombrePortafolio').val($.trim(nombre.text()));
$("#activoFijo_DescripcionActivoFijo").val($.trim(nombre.text()));
document.getElementById("dialog").innerHTML = '<div id="progressbar" class="progressbar" style="display: none;"></div>';
$("#dialog").dialog('close');
});
});
You are using return type as ActionResult in server side method. So this return your entire view, then page will get reload. So this has happening. So please change your methods return type to any other like string, Jsonresult, etc.,  

How to de-serialize JSON data of check box values?

I have multiple check box values in a form. I am serializing the form and send to mvc controller as JSON data. How can i de-serialize the check box values?
This is my html -
#using (Html.BeginForm("SaveOfficeConfiguration", "Offices", FormMethod.Post, new { Id = "frmOfficeConfigSave" }))
{
<div id="divOfficeForm">
<div style="width: auto; height: auto; border: 3px outset silver;">
<table class="mainsectionable" width="100%">
<thead>
<tr>
<th style="text-align: center;">
<center>KCCM Profile Access</center>
</th>
</tr>
<tr>
<td>
#using (Html.BeginForm())
{
IEnumerable<SelectListItem> Brands = ViewBag.GetBrands;
foreach (var item in Brands)
{
#Html.CheckBox("KCCM_Brands", false, new
{
value = item.Value
});
<label>#item.Text</label><br />
}
}
</td>
</tr>
</thead>
</table>
</div>
</div>
}
This is my javascript function-
function SaveOfficeConfigNew() {
var officeID = $('input[name="hdnOfficeID"]').val();
var url = "/OfficeManagement/Offices/SaveOfficeConfiguration?officeID=" + officeID;
ShowWait();
$.ajax({
type: "POST",
url: url,
data: frmOfficeConfigSave.$('input').serialize(),
success: function (data) {
HideWait();
alert(data.msg);
},
error: function (data) {
HideWait();
alert(data.msg);
}
});
applyFilter();
return false;
}
This is my gonna be controller action -
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form)
{
try
{
*/..............
..............*/
return Json(new
{
success = true,
msg = String.Empty,
id = 1
}, JsonRequestBehavior.AllowGet);
}
catch (Exception error)
{
return Json(new
{
success = false,
msg = error.Message,
id = -1
}, JsonRequestBehavior.AllowGet);
}
}
You simply have to receive a List<string> parameter, with the same name you're giving the checkboxes, i.e., KCM_Brands. The Model Binder will deserialize it directly for you.
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form,
List<string> KCM_Brands)
{
....
}
To serialize your form data to post it, use the function suggedted in this post:
JSON object post using form serialize not mapping to c# object
You can use the FormsCollection to retrieve the check box values:
Controller:
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form)
{
var CheckBoxValues = form["KCCM_Brands"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x=>int.Parse(x));
}
For More info Have a look here :
http://www.mindstick.com/Articles/2ee905ba-aea1-4d83-a49d-d8d8fb10c747/?Checkbox%20control%20in%20MVC
Instead of
#Html.CheckBox("KCCM_Brands", false, new
{
value = item.Value
});
use this code to generate checkboxes
<input type="checkbox" name="KCCM_Brands" value="#item.Value" />
The action on your controller should look like this
public ActionResult SaveOfficeConfiguration(int? officeID, List<string> KCCM_Brands)
When you post your form, List<string> KCCM_Brands will be populated only with the values of selected checkboxes.
Also, I don't know if your javascript is correct, but I had to make the following change for it to work
data: $('#frmOfficeConfigSave input').serialize()

Categories

Resources