Get html of view from controller - .NET MVC - html

I want to make previews of one view on a homepage type view. To do so, I'd like to call a ListPreviews Action. I want this action to get the html body of a given view and then take the first hundred characters or so.
How can I access the actual html of a view from a controller?

This should be simple.
In your RouteConfig.cs set the defaults, mine looks like this:
defaults: new { controller = "Home", action = "Index2006", id = UrlParameter.Optional }
For your Controller/Model:
public class AView
{
public string theHtml { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index2005(AView AView)
{
//put breakpoint here to see all the <html> here in view
var result = HttpUtility.UrlDecode(AView.theHtml, System.Text.Encoding.Default);
return Json(new
{
Greeting = "Returning data not used"
}
, #"application/json");
}
For your view:
<!DOCTYPE html>
<html id="PassMe">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2005</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(".btn").click(function () {
var AView = { theHtml: escape($("#PassMe").html()) }; //JSON.stringify($("#PassMe").html())
$.ajax({
url: '/Home/Index2005',
type: 'POST',
data: AView,
success: function (result) {
$("#detail").append(result.Greeting);
},
error: function (result) {
alert('Error');
}
});
});
});
</script>
</head>
<body>
<button style="margin-bottom: 20px;" class="btn btn-default">Click to pass HTML</button>
</body>
</html>

Related

Display contents of SQL Table with Asp.Net Core MVC and FullCalendar

I have setup my app to display events on calendar. However, whilst the correct number of events will display the date and time is always the current date and time rather than what I have input into the SQL db table. Any help with what I am doing wrong would be greatly appreciated. My code is below:
View
#model IEnumerable<wccFacilityBookings.Models.Events>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="calender"></div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span id="eventTitle"></span></h4>
</div>
<div class="modal-body">
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print" />
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/applications/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay : v.IsFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD-
MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-
MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description:</b>' +
calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
}
})
}
})
</script>
}
Controller
// GET: Applications/CalendarView
public IActionResult CalendarView()
{
return View();
}
public JsonResult GetEvents()
{
using (WCCFacilityBookingsContext context = new WCCFacilityBookingsContext())
{
var events =_context.Events.ToList();
return Json(events);
}
}
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace wccFacilityBookings.Models
{
public class Events
{
[Key]
public int EventID { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string ThemeColor { get; set; }
public bool IsFullDay { get; set; }
}
}
Does this have something to do with it being Asp.Net Core?
Yes, in .NET Core 3.x, when you want to pass json from controller to client, it will camel-case all JSON output by default.
To avoid this, you can add the following setting in startup.cs ConfigureServices method:
services.AddMvc()
.AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
Since I added this setting before, the problem did not appear when I tested with your code. If I delete it, your problem will be reproduced.
So you have two solutions, change the field name to camel-case in js, or add the above code in startup.
OK, as always #YongquingYu got me on the right track. I am a 'nuffy' when it come to Ajax and Jquery. My issue, for reasons I don't understand was with capitalization, once I made the 'properties' lower case it worked. Does this have something to do with it being Asp.Net Core? Anyway my code (which is working as desired) is below:
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Applications/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.applicantContactName,
description: v.facility,
start: moment(v.start),
end: v.end != null ? moment(v.end) : null,
color: v.themeColor,
allDay: v.isFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start: </b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End: </b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description: </b>' +
calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
}
})
}
})
</script>
}
// GET: Applications/CalendarView
public IActionResult CalendarView()
{
return View();
}
public JsonResult GetEvents()
{
using (WCCFacilityBookingsContext context = new WCCFacilityBookingsContext())
{
var events = context.BookingApplications.ToList();
return Json(events);
}
}

pass a list of objects via ajax to a MVC controller always sends null

I am probably missing something very simple. I have been working on this for a day and an half now and can not get it to work. I am looping through a table and creating a list of objects to send back to my controller. For some reason I am always receiving a null value in my controller. Here is the java script.
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
url: './ReceivePOLines',
type: "Post",
cache: false,
data: JSON.stringify(items),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
here is the method signature in the controller
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions)
And here is the class ReceivedTransactions
public class RecievedTransactions{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
Here are the results from Fiddler showing what was passed
[{},{"numReceived":"10000","transactionID":"10661768"},{"numReceived":"10000","transactionID":"10661769"},{"numReceived":"2000","transactionID":"10661770"},{"numReceived":"2500","transactionID":"10661771"},{"numReceived":"2500","transactionID":"10661772"},{"numReceived":"2000","transactionID":"10661773"},{"numReceived":"10000","transactionID":"10661774"}]
Any and all help appreciated.
cheers
bob
This is a new answer. Originally, I was getting null, like you. But, now it works the way you want (array of complex objects). Please get this to work for you. If you can't get it to work, although it should, I can create an ASP.NET Fiddle.
public class RecievedTransactions
{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions) // MyArray MyArray
{
return;
}
//you use your own action name
public ActionResult Tut133()
{
return View();
}
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut132</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
//!!changing your url
//url: './ReceivePOLines',
url: "/Home/ReceivePOLines",
type: "Post",
cache: false,
//data: JSON.stringify({ MyArray: items }),
data: JSON.stringify(items),
//expecting back from server-need to remove since we are not getting back data from server
//dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
//alerting success instead of opening window
alert("success");
//window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
})
</script>
</head>
<body>
<table id="grid">
<tr>
<td><input type="text" id="NumReceived1" value="10000" /></td>
<td><input type="text" id="item_TransactionID1" value="10661768" /></td>
</tr>
<tr>
<td><input type="text" id="NumReceived2" value="10000" /></td>
<td><input type="text" id="item_TransactionID2" value="10661769" /></td>
</tr>
</table>
<input type="button" id="theButton" value="Go" />
</body>
</html>

create a search bar jsvue from json object

I want to create a search bar that pulls searches through the data of a json object and displays data to the user. I currently have code that looks like this and it works fine.
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id='app'> <input type='text' v-model='keyword' placeholder='search title'> <button v-on:click="">automotive</button> <div v-for="post in filteredList"> <iframe width="420" height="315" v-bind:src="post.link"> </iframe> <a v-bind:href="post.link">{{post.title}}</a> </div> </div>
<script> "use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Post = function Post(title, link, author, img) {
_classCallCheck(this, Post);
this.title = title; this.link = link; this.author = author; this.img = img; }; var app = new Vue({ el: '#app', data: {
keyword:'',
postList: [
new Post(
'Vue.js',
'https://www.youtube.com/embed/tgbNymZ7vqY',
'Chris',
'https://vuejs.org//images/logo.png'
),
new Post(
'React.js',
'https://www.youtube.com/embed/k3frK9-OiQ0',
'Tim',
'http://daynin.github.io/clojurescript-presentation/img/react-logo.png'
),
new Post(
'Angular.js',
'https://angularjs.org/',
'Sam',
'https://angularjs.org/img/ng-logo.png',
),
new Post(
'Ember.js',
'http://emberjs.com/',
'Rachel',
'http://www.gravatar.com/avatar/0cf15665a9146ba852bf042b0652780a?s=200'
),
new Post(
'Meteor.js',
'https://www.meteor.com/',
'Chris',
'http://hacktivist.in/introduction-to-nodejs-mongodb-meteor/img/meteor.png'
),
new Post(
'Aurelia',
'http://aurelia.io/',
'Tim',
'https://cdn.auth0.com/blog/aurelia-logo.png'
),
new Post(
'Node.js',
'https://nodejs.org/en/',
'A. A. Ron',
'https://code-maven.com/img/node.png'
),
new Post(
'Pusher',
'https://pusher.com/',
'Alex',
'https://avatars1.githubusercontent.com/u/739550?v=3&s=400'
),
new Post(
'Feathers.js',
'http://feathersjs.com/',
'Chuck',
'https://cdn.worldvectorlogo.com/logos/feathersjs.svg'
), ] }, methods: {
}, computed:{
filteredList(){
return this.postList.filter((post) => {
return post.title.toLowerCase().includes(this.keyword.toLowerCase());
});
} } })
</script> </body> <html>
Ignore what the links are going to it doesnt matter. The problem Im having however is getting this to work from an external source via an axios request. I've done axios request before and got json data back but im struggling to make this search feature work with it. The following is an example of the broken code (ignore the v-on:click its not set up yet. ignore the fact there are no videos I can deal with that later I just need the search feature to work with an json data from an axios request) but I keep getting errors like 'type error : this.item is not defined' and 'object error' anyway heres the code:
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id='app'>
<input type='text' v-model='keyword' placeholder='search item'>
<button v-on:click="">automotive</button>
<div v-for="item in filteredList">
<p>{{item.name}}</p>
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
keyword:'',
itemList: '',
},
created: function() {
this.loaddata();
},
methods: {
loaddata: function(){
var vueapp = this;
axios.get('https://jsonplaceholder.typicode.com/users').then(function (response){
vueapp.itemList = response.data;
})
},
},
computed:{
filteredList(){
return this.item.filter((item) => {
return item.name.toLowerCase().includes(this.keyword.toLowerCase());
});
}
}
})
</script>
</body>
<html>
You don't have item declared in your data. you can't call this.item.filter in your filteredList() method when you don't have it declared.
You can change your filteredList with this.itemList.filter() which is the list being loaded in loaddata()

Polymer basic issue

Hi I'm trying to execute a basic polymer program. Getting the below exception at step var el = new HelloElement();. Also the element itself is not attached to the page.
Exception
Uncaught TypeError: Illegal constructor
at PropertyAccessors (property-accessors.html:119)
at TemplateStamp (template-stamp.html:119)
at PropertyEffects (property-effects.html:1075)
at PolymerElement (element-mixin.html:459)
at GestureEventListeners (gesture-event-listeners.html:40)
at LegacyElement (legacy-element-mixin.html:69)
at PolymerGenerated (class.html:137)
at (index):18
at html-imports.js:580
at html-imports.js:617
CODE
<!DOCTYPE html>
<html>
<head>
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"> </script>
<link rel="import" href="bower_components/polymer/polymer.html"/>
</head>
<body>
<script>
HTMLImports.whenReady( function () {
HelloElement = Polymer.Class({
is: "hello-element",
created: function () {
this.textContent = "Hello World";
}
});
document.registerElement('hello-element', HelloElement);
var el = new HelloElement();
document.querySelector("body").appendChild(el);
})
</script>
</body>
</html
Try using the new class syntax as below:
HTMLImports.whenReady(function() {
class MyElement extends Polymer.Element {
static get is() { return 'my-element'; }
static get properties() {
return {
prop: {
type: String
}
}
}
constructor() {
super();
this.prop = 'my-element'
}
}
customElements.define(MyElement.is, MyElement);
var el = new MyElement();
el.textContent = 'my-element';
document.querySelector("body").appendChild(el);
});
JSBin: http://jsbin.com/vefelacada/edit?html,console,output
See more informations at: https://www.polymer-project.org/2.0/docs/devguide/registering-elements
=== Edit
If you really want to use Polymer 1.0 syntax, you should probably do something like: (not 100% sure what the error really means)
Polymer({
is: "hello-element",
});
var el = document.createElement("hello-element");
document.querySelector("body").appendChild(el);
el.textContent = 'my-element';
http://jsbin.com/zihayumaqo/edit?html,console,output

"Unknown Provider" AngularJS ngRoute

I'm working for the first time with Angular.js. I already search too many articles in order to correct this error. I receive the following error when my Index.html is loaded:
Here is the code:
report-module.js
angular.module('reportTemplateApp', [
'reportTemplateApp.services',
'reportTemplateApp.controllers',
'ngRoute'
]).
config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/slide1/:auditId', {
templateUrl: 'slide1.html',
controller: 'MainSlideController',
controllerAs: 'main'
})
.when('/slide3/:auditId/sl/:slideId', {
templateUrl: 'slide3.html',
controller: 'CommonSlidesController',
controllerAs: 'commons'
});
$locationProvider.html5Mode(true);
}]);
report-controller.js
angular.module('reportTemplateApp.controllers', []).
controller('CommonSlidesController', '$routeParams', function ($scope, $routeParams, auditAPIservice) {
$scope.id = $routeParams;
$scope.slideId;
$scope.slide = [];
//CANCEL EDIT
$scope.cancelSave = function () {
$scope.mainList = $scope.backupList;
}
//SAVE DATA
$scope.saveSlide = function () {
try {
auditAPIservice.ItemsData($scope.mainList).then(function (response) {
if (response.message = "Success") {
}
else {
$scope.mainList = $scope.backupList;
}
});
} catch (ex) {
$scope.showToast('UPS! Something happen ' + ex.message);
}
}
//GET DATA
reportAPIservice.getSlide(2, 3).then(function (response) {
if (response.message = "Success") {
$scope.mainList = response.data.ReportSlideInfo
angular.copy($scope.mainList, $scope.backupList);
}
else {
//SOME ERROR SHOWING HERE
}
});
$scope.showToast = function (message) {
angular.element(document).ready(function () {
toast(message, 4000);
});
}
}).
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="../Scripts/jquery-1.7.1.js"></script>
<script src="../Scripts/materialize/materialize.min.js"></script>
<title></title>
<link rel="stylesheet" type="text/css" href="../Content/materialize/materialize.css" />
</head>
<body ng-app="reportTemplateApp">
<script>
$(document).ready(function () {
$(".button-collapse").sideNav();
$('.collapsible').collapsible();
});
</script>
Text Link<br/>
<div ng-view></div>
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-route.js"></script>
<script src="~/Scripts/angular-resource.js"></script>
<script src="../Scripts/SPS/Report/report-module.js"></script>
<script src="../Scripts/SPS/Report/report-controller.js"></script>
<script src="../Scripts/SPS/Report/report-service.js"></script>
</body>
</html>
I don't know what it's wrong. Another thing, the error shows when I add in the Index page, if I remove it no error is present.
I was able to fix this. I had (I don't know why) in the project mixed versions of the angular.js(1.2.23) and angular-route.js (1.3.8). After change one with the same version of the other there is no error and routing works.