I can't seem to get anything displayed in my div which has the attribute "ng-view".
Here is my controller;
(function () {
var app = angular.module("userViewer", []);
var MainController = function ($scope, $location) {
console.log("Main controller");
$scope.search = function () {
console.log("User ID: " + $scope.userid);
//Right Route Here
};
};
app.controller("MainController", MainController);
}());
Here is my app.js:
(function() {
var app = angular.module("userViewer", ['ngRoute']);
console.log("Test route");
app.config(function($routeProvider) {
$routeProvider.when("/main", {
templateUrl: "html/main.html",
controller: "MainController"
})
.otherwise({ redirectTo: "/main" });
});
}());
My master template:
<!DOCTYPE html>
<html ng-app="userViewer" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
#Scripts.Render("~/bundles/angular")
</head>
<body>
#RenderBody()
</body>
</html>
My angular SPA main page html body:
<h2>Header</h2>
<div ng-view>
</div>
My main.html
<div>
<form name="searchUser" ng-submit="search()">
<input type="search" required ng-model="userid" placeholder="User ID to find" />
<input type="submit" value="Search" />
</form>
</div>
My console.log within app.js "Test route prints but when I navigate to URL/#/main nothing is shown.
Just the word "Header" and the main.html view is not loaded atall.
There is also no errors displayed in the console.
Can anyone give me some advice?
In your controller you are doing this
var app = angular.module("userViewer", []);
When you put the [] in there you are creating a new module. Try
var app = angular.module("userViewer");
to reference your existing one.
(function() {
var app = angular.module("userViewer", ['ngRoute']);
console.log("Test route");
app.config(function($routeProvider) {
$routeProvider.when("/main", {
templateUrl: "/html/main.html", <-- try to locate the view starting from the root path of the app
controller: "MainController"
})
.otherwise({ redirectTo: "/main" });
});
}());
try to define your controller as:
angular.module('userViewer').controller('MainController', ['$scope', '$location', function ($scope, $location) {
//your code here
}]);
change app.js to
(function () {
var MainController = function ($scope, $location) {
console.log("Main controller");
$scope.search = function () {
console.log("User ID: " + $scope.userid);
//Right Route Here
};
};
app.controller("MainController", MainController);
}());
Related
I am learning web api where I have created a html page and I want to get <ul> list in my html page.
To call api i have used Jquery ajax call to do so but seems not working. I debugged Jquery but getting no error.
Please suggest me where i am going wrong.
My html code
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
var listitem = $('#ulEmployees');
$('#btn').click(function () {
debugger;
$.ajax({
Type: 'GET',
url: 'api/employees',
dataType: JSON,
success: function (data) {
listitem.empty();
debugger;
$.each(data, function (index, val) {
var fullname = val.FirstName + ' ' + val.LastName;
listitem.append('<li>' + fullname + '</li>');
});
}
});
});
$('#btnClear').click(function () {
listitem.empty();
});
});
</script>
</head>
<body>
<input id="btn" value="Get All Employees" type="button" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees"></ul>
</body>
</html>
Web api GET method
public class EmployeesController : ApiController
{
public HttpResponseMessage Get(string gender="All")
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
switch(gender.ToLower())
{
case "all":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.ToList());
case "male":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "male").ToList());
case "female":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "female").ToList());
default:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not found");
}
}
}
}
The datatype should not be passed. Your function should be like below with out datatype as JSON. Internally in jquery the call will fail while it is trying to convert datatype with .toLower function.
$('#btn').click(function () {
debugger;
$.ajax({
Type: 'GET',
url: 'api/employees',
success: function (data) {
listitem.empty();
debugger;
$.each(data, function (index, val) {
var fullname = val.FirstName + ' ' + val.LastName;
listitem.append('<li>' + fullname + '</li>');
});
}
});
});
I am new to AngularJS programming. Any help would be highly appreciated.
A HTML text box will be created each time a HTML button is clicked.
In webform1.aspx submit button click even cannot capture the values entered in those text boxes.
I used request.form, loop through controls in the form1 but cannot find dynamically created controls.
How to post and see the data entered in those textboxes from code behind?
Please find the code below:
webform1.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js"></script>
</head>
<body>
<form id="form1" runat="`server">
<div>
<div ng-app="myApp" ng-controller="myCtrl">
<li ng-repeat="element in elements ">
<input type="text" ng-model="element.id" runat=server/>
</li>
<input type="button" value="+" ng-click="newItem()" />
</div>
</form>
</body>
<script language="JavaScript">
var app = angular. Module('myApp', []);
app.controller('myCtrl', function ($scope) {
var counter = 0;
$scope.elements = [{ id: counter, value: ''}];
$scope.newItem = function () {
if ($scope.elements[counter].value != '') {
counter++;
var str1 = 'txtdynamic';
str1 += counter;
$scope.elements.push({ id: str1, value: '' });
}
}
});
</script>
</html>
webform1.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
//get the html ng repeat textbox control values
}
Try it the right way my friend. Compare the following codes with your approach.
> demo fiddle.
View
<div ng-controller="myCtrl">
<form id="form1" runat="`server">
<div>
<div ng-app="myApp" ng-controller="myCtrl">
<li ng-repeat="element in elements">
<input type="text" ng-model="elements[element.id].value" runat=server/>
</li>
<input type="button" value="+" ng-click="newItem()" />
<input type="button" value="send" ng-click="ButtonClick()" />
</div>
</div>
</form>
</div>
AngularJS application
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var counter = 0;
$scope.elements = [{
id: counter,
value: ''
}];
$scope.newItem = function() {
if ($scope.elements[counter].value != '') {
counter++;
var str1 = 'txtdynamic';
str1 += counter;
$scope.elements.push({
id: str1,
value: ''
});
}
}
$scope.ButtonClick = function() {
var post = $http({
method: "POST",
url: "/Home/AjaxMethod",
dataType: 'json',
data: {
id: angular.isDefined($scope.elements[0]) ? $scope.elements[0].value : null
},
headers: {
"Content-Type": "application/json"
}
});
}
});
I'm trying to implement the autocomplete jQuery UI function in a Bootstrap modal window, but it does not work.
screenshot module
console debug
Take the steps of not returning a partial view, also already implement jQuery CSS styles, the truth works for me in full views, but why when calling a modal window does not? any help for me?
My Script of where I call the Modal window:
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "a.dialog-window", null, function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$('#AgregarProducto').modal('show');
}
else {
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
}).success(function () { $('input:text:visible:first').focus(); });
}
});
});
</script>
My Modal Windows:
<div class="form-group">
<div class="col-md-10">
<input type="text" name="producto" id="producto" />
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
$("#producto").autocomplete({
source: "/Salidas/BuscarProducto"
});
});
</script>
}
My Controller:
public JsonResult BuscarProducto(string term)
{
using (DataContext db = new DataContext())
{
var resultado = db.Productos.Where(x => x.v_Nombre.Contains(term)).Select(y => y.v_Nombre).Take(5).ToList();
return Json(resultado, JsonRequestBehavior.AllowGet);
}
}
Try to add an event handler for shown.bs.modal before you show the modal itself.
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "a.dialog-window", null, function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$('#AgregarProducto').on('shown.bs.modal', function () {
$("#producto").autocomplete({
source: "/Salidas/BuscarProducto"
});
}
$('#AgregarProducto').modal('show');
}
else {
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
}).success(function () { $('input:text:visible:first').focus(); });
}
});
});
</script>
I'm still new to asp.net mvc, i want to delete list of partial view, the delete is working but i must reload the entire page to show the new list
What I want is the partial view show the new list after delete without load the entire page, so only the partial view is updated
Here is my code:
My view content some of partial view :
#model cc.Models.User
#{
Layout = "~/Views/Shared/_MemberLayout.cshtml";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")" type="text/javascript"></script>
<body class="container body-content">
<div id="partialView1">
#Html.Action(...)
</div>
<div id="partialView2">
#Html.Action(...)
</div>
<div id="partialView4">
#Html.Action(...)
</div>
<div id="partialView3" class="col-md-8 col-sm-1">
#Html.Action("UserHistory", "User")
</div>
</body>
Here is my partial view for UserHistory I tried to use ajax but it's not work. I already tried to use
$(this).closest('.historyRow').remove();
and
$("a.deleteHistory").live("click", function () {
$(this).parents("div.historyRow:first").remove();
return false;
});
Here is my code :
#model cc.Models.UserHistory
#{
Layout = null;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")" type="text/javascript"></script>
<div id="formHistory">
<div id="historyDetail">
<div id="editDataHistoryUser">
#foreach (var item in Model.History)
{
#Html.Partial("UserHistoryDetail", item)
}
</div>
#Html.ActionLink("Add Form", "AddUserHistory", null, new { id = "btnFormHistory" })
</div>
</div>
<script type="text/javascript">
$("#btnFormHistory").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editDataHistoryUser").append(html); }
});
return false;
});
$('#formHistory').on('click', '.deleteHistory', function () {
var id = $(this).data('id');
if (id == 0) {
$(this).closest('.historyRow').remove();
//$("a.deleteHistory").live("click", function () {
// $(this).parents("div.historyRow:first").remove();
// return false;
//});
} else {
var url = '#Url.Action("DeleteUserHistory", "User")';
$.post(url, { ID: id }, function (response) {
if (response) {
$(this).closest('.historyRow').remove();
//$("a.deleteHistory").live("click", function () {
// $(this).parents("div.historyRow:first").remove();
// return false;
//});
}
}).fail(function (response) {
});
}
});
</script>
Here is my UserHistoryDetail Code :
#model cc.Models.IUserHistory
#{
Layout = null;
}
<div id="formUserHistoryDetail">
#using (Ajax.BeginForm("UserHistoryDetail", "User", new AjaxOptions { HttpMethod = "POST" }))
{
<div id="historyRow">
<div>#Html.LabelFor(model => model.IDHistory, new { style = "display:none;" })</div>
...
delete
</div>
}
</div>
And here is my JsonResult when button delete clicked :
[HttpPost]
public JsonResult DeleteUserHistory(string ID)
{
db.delUserHistory(ID);
return Json(true);
}
I still cannot find the solution for this , or maybe i used ajax in wrong way, any suggestion?
Let's assume that the DeleteUserHistory post url is '/[Controller]/': '/UserHistory'
$('.deleteHistory').click(function(){
var url = '/UserHistory';
$.ajax({
type: "POST",
url: url,
data: data,
success: onSuccessCallback
});
});
What you should really do is use WebApi to manage data and use the views to display.
As for the delete, use method type 'delete' instead of 'post'. Post should be used for "adds".
I am trying to do something like, i have an index view which has some tags on each on one when click i want to return a partial view and append it to the div in main index.cshtml view
my code i below
Index.cshtml
#model OyeAPI.Models.User
#{
object user = Session["userId"];
ViewBag.Title = "Index";
}
<link href="#Url.Content("~/Content/css/style.css")" rel="stylesheet"/>
<div class="main_Container">
#if (Session["userId"] == null) {
<div class="login_div">
#Html.Partial("~/Views/Shared/_signin.cshtml")
</div>
}else
{
<div style="height:100px;">
<p>OyePortal</p>
</div>
// <p>#Html.ActionLink("clickme", "callLogs", "contactWeb")</p>
<div style="position:relative; left:400px;">
<div>
<p id="contacts">Contacts</p> | <p id="callLogs">Call Logs</p> |
<p id="messages">Phone Messages</p> | <p >Groups</p>
</div>
<div id="container_inner_frame">
<h1>Welcome fuck it clickme </h1>
</div>
</div>
}
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
#*<script src="#Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>*#4
<script type="text/javascript">
$("#contacts").on("click", function () {
$("#container_inner_frame").html('#Html.Partial("~/Views/Shared/_contacts.cshtml")');
});
$("#callLogs").on("click", function () {
$("#container_inner_frame").html('#Html.Partial("~/Views/Shared/_callLogs.cshtml")');
});
$("#messages").on("click", function () {
$("#container_inner_frame").html('#Html.Partial("~/Views/Shared/_Phonemessages.cshtml")');
});
</script>
shared View _callLogs.cshtml
#model OyeAPI.Models.CallLogs
#{
List<Model.CallLogsModel> ListCallLogs = (List<Model.CallLogsModel>)ViewData["Data"];
Int64 CallID = 0;
string callNumber = null;
string callDuration = null;
string callType = null;
string date = null;
string daytime = null;
}
<div class="main_Container">
<div>
<div>
<ul>
<li>Contact ID</li><li>Contact Name </li><li>Contact Number</li>
</ul>
</div>
#if (ListCallLogs != null)
{
foreach (var item in ListCallLogs)
{
CallID = item.CallId;
callNumber = item.PhoneNumber;
callDuration = item.CallDuration;
callType = item.CallType;
date = item.CallDate.ToShortDateString();
daytime = item.CallDayTime.ToShortTimeString();
<div>
<ul>
<li>#CallID</li><li>#callNumber </li><li>#callDuration</li><li>#callType</li><li>#date </li><li>#daytime</li>
</ul>
</div>
}
}
else
{
<p>Empty String list no messages</p>
}
</div>
</div>
Controller contactWeb function callLogs
[HttpPost]
[AllowAnonymous]
public ActionResult callLogs()
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<CallLogsModel> callModel = new List<CallLogsModel>();
ICallLogs callLogObject = new CallLogsBLO();
callModel = callLogObject.GetCallLogs(userID);
ViewData["Data"] = callModel;
}
catch (Exception e)
{
}
return PartialView("_callLogs", ViewData["Data"]);
}
But its not working, when i run the code before login it hit the _callLogs shared view first and after that it show the login screen and when i click the callLogs it dosen't display any thing. i my be missing something
Your approach is not right:
you are writing jquery event, you have to send an ajax call to an action and return partial view of CallLogs and then append it to container div.
do like this:
$("#callLogs").on("click", function () {
$("#container_inner_frame").load('#Url.Action("callLogs","YOurController")');
});
or like this:
$("#callLogs").on("click", function () {
$.ajax({
url: '#Url.Action("callLogs", "YourControllerName")',
success: function (response) {
$("#container_inner_frame").html(response);
}
error: function () {
alert("error occured");
}
});
});
If you use the jQuery unobtrusive Ajax library, you should be able to do something as simple as this to load content from a partial on a button/link click. Note that you need to have a controller which returns a PartialViewResult (this can then reference your view) :
#Ajax.ActionLink("Click Me", "Action", "Controller", new AjaxOptions{ InsertionMode=InsertionMode.InsertAfter, UpdateTargetId="MyTargetDivId"})
<div id="MyTargetDivId"></div>
Try this :
$("#callLogs").on("click", function () {
$.ajax({
url: '#Url.Action("callLogs", "YourController")',
type: 'get',
datatype: 'json',
success: function (data) {
$('div#container_inner_frame').html(data);
}
});
});