Gets Data in Json Format From AngularJs Controller - c#

I am having a hard time with AngularJs. It works accordingly in some cases for me and when I try to change the template of the project, it doesn't work anymore. Here is the scenario - I have a controller in ASP.NET MVC that returns the list of products in Json format and finally I call this controller using AngularJs controller as follows:
C#:
public JsonResult GetProducts()
{
var result = (from c in db.Products
select new { c.ProductName, c.Price }).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
AngularJs:
var app = angular.module('app', []);
app.controller('ProductController', function ($scope, ProductService) {
$scope.Products = null;
ProductService.GetProducts().then(function (d) {
$scope.Products = d.data;
}, function () {
alert('Failed');
});
});
app.factory('ProductService', function ($http) {
var factory = {};
factory.GetProducts = function () {
return $http.get('/Product/GetProducts');
}
return factory;
});
In the UI, I've used the following:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Get Products</title>
<script src="~/Scripts/angular.js"></script>
<script src="../AngularFile/AddToCart.js"></script>
</head>
<body>
<div>
<h2>Get Products</h2>
<div ng-app="app" class="container">
<br /><br />
<br /><br />
<input type="text" ng-model="name" />
<h1>{{ name }}</h1>
<div ng-controller="ProductController">
<table class="table table-responsive" ng-repeat="m in Products">
<tr>
<td>{{ m.ProductName }}</td>
<td>{{ m.Price }}</td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
The output I am getting is this:
I am not sure what I am doing wrong. In my earlier project, using the same code, it shows products properly but right now, I am getting data in Json format. Is this common and anyone faced like this before?
Note: If I change the method type from JsonResult to ActionResult, it shows nothing.

Related

How to get Json result in to the table using angularJs

I'm trying to retrieve whole table in mvc5 using angularJS.
Data in Json result is being displayed but not in the table as I wanted.
I'm using mvc5 and angularjs(1.x) to retrive the data from sql server
Here's the Data Access Layer code:
public List<Employee> ShowAllEmployee()
{
List<Employee> prdList = userdb.Employees.ToList();
return prdList;
}
Here's the HomeController method:
public JsonResult AllEmployee()
{
repo = new Employee_DAL.EmpRepo();
var hotList = repo.ShowAllEmployee();
List<Models.Employee> mList = new List<Models.Employee>();
foreach (var hotl in hotList)
{
Models.Employee hotLocal = new Models.Employee();
hotLocal.EmployeeId = hotl.EmployeeId;
hotLocal.FirstName = hotl.FirstName;
hotLocal.LastName = hotl.LastName;
hotLocal.Designation = hotl.Designation;
//hotLocal.Description = hotl.Description;
hotLocal.Country = hotl.Country;
hotLocal.Gender = hotl.Gender;
//hotLocal.Rating = hotl.Rating;
//hotLocal.Email = hotl.Email;
mList.Add(hotLocal);
}
return Json(mList, JsonRequestBehavior.AllowGet);
}
Here's the script ( angular) code:
var myApp = angular.module('MyModule', []);
myApp.controller('DBcontroller', function ($scope, $http) {
$http.get('/Home/AllEmployee') // added an '/' along with deleting Controller portion
.then(function (response) {
$scope.students = response.data
})
})
Here's my view(cshtml):
#{
Layout = null;
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Customs/angular.min.js"></script>
<script src="~/Customs/Scripts.js"></script>
<title>AllEmployee</title>
</head>
<body ng-app="myApp">
<div ng-controller="DBcontroller">
<table class="table-bordered">
<tr>
<th>Emp No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Designation</th>
<th>Country</th>
<th>Gender</th>
</tr>
<tr ng-repeat="e in students" #*ng-class-even="'even'" ng-class-odd="'odd'"*#>
<td>{{e.EmployeeId}}</td>
<td>{{e.FirstName}}</td>
<td>{{e.LastName}}</td>
<td>{{e.Designation}}</td>
<td>{{e.Country}}</td>
<td>{{e.Gender}}</td>
</tr>
</table>
</div>
</body>
</html>
I expect the jsonresult to be displayed in a table. Not directly like this in the browser.Screenshot of my current output

I need help for autocompletion in a textbox with id and text

I am a beginner in asp.net and I'm trying to add a search bar with autocompletion.
I want the result to return a list of object, result of a stored procedure on two tables with more than 200.000 rows each (top 30 result for the autocompletion), with 2 fields : a label (Resultat) and an Id (IdRes).
I managed to call my function, I get my result, but the autocomplete popup does not show or in a wrong way.
Here is the code of my _layout.cshtml:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - CLAP : le colloque du cinéma</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="Scripts/jquery-3.3.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#navinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home/RechercheAutoComplete",
data: "{'term':'" + $("#navinput").val() + "'}",
datatype: "json",
success: function (data) {
response($.map(data, function (value, key) {
return {
label: value.Resulat,
value: value.Resulat
}
}));
},
error: function (result) {
alert("Error");
}
});
}
});
});
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-collapse collapse">
...
<div class="navbar-form navbar-left" role="search">
<div class="formgroup">
<input class="form-control" id="navinput" name="navinput" runat="server" type="text" width="512" placeholder="Search..." />
<button class="btn btn-default glyphicon glyphicon-search" id="navsearchbtn" runat="server" OnClick="navSearch" type="submit" />
</div>
</div>
...
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
</div>
<div class="footer">
<p>© #DateTime.Now.Year - CLAP</p>
</div>
#RenderSection("scripts", required: false)
</body>
</html>
So, with this code, It shows me a popup menu in the left top corner of the browser, instead of under my textbox and it displays the ResId instead of Resultat.
What am I doing wrong and how can I fix it ? I want the user to select a label but return the Id.
So technically you need to do is for Every Key Enter in textbox
for example
H of "Hamza" you take this 'H' from TextBox and make an Ajax call and make a function in controller to return JSON result by querying the database using SQL like query which when using C# we can use LINQ
var nameSuggestion = customers.Where(c => c.Name.Contains("H")).tolist();
So this Method will return the JSON result and you can then AutoFill Your ListBox with suggestions using JQUERY or JAVASCRIPT,So you Keep on typing for every Key-Down Data-Base will be queried and you will get the changed suggestion side by side when you put in the letters one by one
H
A
M
Z
A
This is how i did in my project and it worked perfectly.
Why not add a datalist, with all the desired options? That way if you search, it will show all the possible options, depending on the current content.
<input list="MyDataList"/>
<datalist id="MyDataList">
<option>option1</option>
<option>option2</option>
<option>option3</option>
</datalist>
I suggest you have a <div> with an ID. Then you use ajax to call a PartialView (by ActionResult-Method) which creates the <datalist> element with all the options. Then in the ajax-result-function you can populate the div like this:
$("#IdOfTheDiv").html(result);
Or alternatively maby use this: http://easyautocomplete.com/ (Haven't tried it)

How to use MVC Model binding with an Angular ng-bind attribute

In my view I have a tag with an ng-bind attribute that is showing the correct boolean value:
<span id="ShowFlag" name="ShowFlag" ng-bind="session.view.showFlag"></span>
When the form is posted on the server side I would like to bind this to a property on the relevant model.
public bool ShowFlag { get; set; }
However, this is always returning false, whereas the value shown in Span tag is showing correctly as true on the page. Is there something obvious I'm missing here?
I think you're something you're missing about how AngularJs binding works. if you want to get a value from the server into an angular model you can use Razor to get that data into JavaScript (the best place is in your Angular controller.)
Here is a quick sample I put together.
This is code from the MVC Controller. In this example we are using Model data and ViewBag data.
public ActionResult Index()
{
dynamic model = new ExpandoObject();
model.ShowFlag = "True";
ViewBag.ShowFlag = "ViewBag True";
return View(model);
}
This is what the view looks like including reference so Angular, JQuery and the code for the AngularJs app and controller:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Demo</title>
</head>
<body>
<div>
<h2>Sample For Stack Overflow</h2>
<div ng-app="glennapp">
<div ng-controller="testController">
<input type="text" ng-model="showFlag" />
<input type="text" ng-model="showFlag2" />
<div>
<span ng-bind="showFlag" ></span>
<span ng-bind="showFlag2" ></span>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="//code.angularjs.org/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var mainApp = angular.module('glennapp', ['glennControllers']);
var glennControllers = angular.module('glennControllers', []);
glennControllers.controller('testController', ['$scope', function ($scope) {
$scope.showFlag = '#ViewBag.ShowFlag';
$scope.showFlag2 = '#Model.ShowFlag';
}]);
</script>
</body>
</html>
Another option would be to create an MVC action that returns JsonResult and then write some JavaScript to make an Ajax call and retrieve the data.
When posting a form only input and select tag values are passed to the server
in you case ShowFlag is a span, so you need to make it an input:
<input type="checkbox" id="ShowFlag" name="ShowFlag" ng-bind="session.view.showFlag"/>
If you are posting to server with ajax, make sure that you serialize your model properly:
for example for the following action:
public ActionResult (FlagsConatiner container)
{
//
}
public class FlagsConatiner
{
public bool ShowFlag { get; set; }
}
Serialized model should look like this:
{
"ShowFlag":"true"
}
As pointed out above, you must use an input for the binding to be successful. I used the following which is now working:
<input type="hidden" id="ShowFlag" name="ShowFlag" ng-value="session.view.showFlag">

How to retrieve binarydata source of an image in asp.net

I want to get image preview before uploading any image in my asp.net webform. I am doing this by the following code. But after clicking Save button I want to upload the image to the server. In my codebehind I am getting src="" for <img>. What can I do to get the binarydata back to save my file.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var link = $(fileInput).siblings('.thumb').attr('src');
alert(link);
var img = document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br />
<img id="thumbnil" class="thumb" style="width: 20%; margin-top: 10px;" src="" alt="image" runat="server"/>
<asp:Button runat="server" Text="Save" OnClick="Unnamed_Click"/>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Thanks in advance..
### Undated whole Answer ###
Option 1:
dont read the img-tag src-attribute, the client cant update it on server side and it wont be "post-back". use an input field like this
<form...>
...
<input class="image-data" type="hidden" id="imageString" runat="server" />
...
</form>
and in the Js-Code add this dataurl as value of this field.
...
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
//... add this, it's searches for the input-field, to be able to post the String to the Server
$(".image-data").val(e.target.result);
};
...
Update:
On the Server you can read the Data like this.
string imageData = imageString.Value;
Option 2:
you could also do this:
alter your asp.net-file
<!-- add enctype=... -->
<form id="form1" runat="server" enctype="multipart/form-data">
...
<!-- add name=... -->
<input type="file" accept="image/*" onchange="showMyImage(this)" name="uploadImage" />
...
in the Codebehind:
HttpPostedFile imageFile= Request.Files["uploadImage"];
if (imageFile && imageFile.ContentLength > 0)
{
// ... Use the imageFile variable as you please
}
Which Option depends, what you want to do with the data.

How to provide auto complete within a textbox without using ajax extension or webservice?

I have a textbox on my web form. I want to bind this textbox with the column "name" in my database table. I want that when the user will type alphabets in this textbox then based on the data matching with the alphabet the suggestion will be given in a dropdown just like any other search engine. I want to do it without using Ajax Autocomplete extender or any web services. I tried doing this through Jquery, but I did it with static names. I want these names to be fetched from database. please guide me how can I do this?
aspx page-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function () {
var items = [
"Argo",
"Alex",
"Mike",
"Mark",
"Joseph",
"John",
"Alex",
"Marrie"
];
$("#TextBox1").autocomplete({
source: items
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Name:</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
</tr>
</table>
</div>
</form>
</body>
</html>
If you want something to be read from database, there should be some server side script, hence you will need the webservice to do so.
This is how it can be done-
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
var items=[<%=autotag %>];
$("#TextBox1").autocomplete({
source:items
});
});
</script>
<body>
<form id="form1" runat="server">
<div class="article" id="article">
<table>
<tr>
<td>Name:</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
</tr>
</table>
</div>
</form>
</body>
and in cs code-
public string autotag="";
protected void Page_Load(object sender, EventArgs e)
{
bind1();
}
public void bind1()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
con.Open();
string query="select name from tbl_data_show";
SqlCommand cmd=new SqlCommand(query,con);
SqlDataReader dr=cmd.ExecuteReader();
dr.Read();
while(dr.Read())
{
if(string.IsNullOrEmpty(autotag))
{
autotag+="\""+dr["name"].ToString()+"\"";
}
else
{
autotag+=", \""+dr["name"].ToString()+"\"";
}
}
}

Categories