JSON List ASP.net MVC - javascript

I have /Views/Movies/Index.cshtml with
<input type="button" id="getmoviex" value="Get moviex" />
<ul id="moviex_list"/>
<p>
Title: #Html.TextBox("SearchTitle") <br />
</p>
I have /Controllers/MoviesController.cs with
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult moviex(string SearchGenre, string SearchTitle, string SearchActor)
{
var db = new CinemaContext();
db.Configuration.ProxyCreationEnabled = false;
var Movie = from m in db.Movie
select m;
if (!String.IsNullOrEmpty(SearchTitle))
{
Movie = Movie.Where(s => s.Title.Contains(SearchTitle));
}
return Json(db.Movie.ToList(), JsonRequestBehavior.AllowGet);
}
I have Javascript.js with
$(document).ready(function () {
$('#getmoviex').click(function () {
$.getJSON("/Movies", null, getmoviex);
});
});
Have I correctly written /Movies? Or this should be /Views/Movies?
function getmoviex(moviex) {
$("#moviex_list").text("");
$.each(moviex, function (i) {
$("#moviex_list").append("<li>" + this + "</li>");
});
}
How can I display info or list info from my query? Or view some output with error?

First make sure you button click does not trigger a request to server. Preventing default behavior is a standard way of doing it:
$('#getmoviex').click(function (event) {
$.getJSON("/Movies", null, getmoviex);
event.preventDefault();
});
As for the URL, it should not be to view, but to action instead. Your action is moviex and controller is Movies, so
$.getJSON("/Movies/moviex", null, getmoviex);
The rest looks fine, so that should do it.

you need to pass your arguments as well in url (GET).
Something like this could work:
$('#getmoviex').click(function(event) {
event.preventDefault();
$.getJSON("/Movies/moviex?SearchGenre=yuorgenre&SearchTitle=Cal&SearchActor=youractor", function(moviex) {
var lis;
//please check the console
console.log(moviex);
$.each(moviex, function(b) {
lis += "<li id='" + b.Id + "'>" + b.Title + "</li>");
}); document.getElementById("moviex_list").innerHTML += lis;
});
});
To avoid circular reference in Serializing you may use:
if (String.IsNullOrEmpty(SearchTitle)) {
return View("Error");
}
var db = new CinemaContext();
var Movie = (from m in db.Movie
Where m.Title.Contains(SearchTitle)
select new {
Id = m.MovieID,
Title = m.Title // can add more properties
}).ToList();
return Json(Movie, JsonRequestBehavior.AllowGet);

Related

Why is my comment being rendered as a JSON object and not appended to the DOM

I am creating a comment with Jquery and want to append it to the page without a page reload. I have a commentConfirm prototype function catching it before the post. I cannot use remote:true on this project so here is the code :
$(function createComment() {
$("#new_comment").on("submit", function(e) {
const values = {
description: $('#comment_description').val(),
rating: $('#comment_rating').val()
};
const newComment = new Comment(values);
newComment.commentConfirm();
});
});
function Comment(comment) {
this.description = comment.description;
this.rating = comment.rating;
}
Comment.prototype.commentConfirm = function(e) {
let doIt = confirm(`You are about to comment: "${this.description}" and give a rating of: ${this.rating} stars`);
if(!doIt)
return;
let params = {
'comment[description]': this.description,
'comment[rating]': this.rating
};
$.post(this.action, params).success(function(response) {
$('div.comments_container').append('<div class="new_comment_' + `${response.id}` + '"> </div>')
$('div.new_comment_'+ `${response.id}`).append('<h3 class="cheading">' + `${response.user.name}` + ' gives ' + `${response.rating}` + ' out of 5 stars! </h3>')
$('div.new_comment_'+ `${response.id}`).append('<p class="cdescription">' + `${response.description}` + '</p>')
$('div.new_comment_'+ `${response.id}`).append('<a class="ecomment" href="/recipes/' + `${response.recipe_id}` + '/comments/' + `${response.id}` + '/edit">Edit</a>' + " ")
$('div.new_comment_'+ `${response.id}`).append('<a class="dcomment" rel="nofollow" data-method="delete" href="/comments/' + `${response.id}` + '">Delete</a>')
$('form#new_comment')[0].reset();
});
};
Not sure if this is causing an issue but here is my create function in the controller:
def create
if logged_in?
comment = Comment.new(comment_params)
comment.recipe = find_by_recipe_id
comment.user = current_user
if comment.description.empty? || comment.rating == nil
redirect_to recipe_path(comment.recipe), alert: "Please fill out all fields"
else
comment.save
render json: comment.to_json(only: [:rating, :description, :id, :recipe_id],
include: [user: { only: [:name]}])
end
else
redirect_to login_path, alert: "You must be logged in to comment"
end
end
Any help with his problem would be greatly appreciated!!
here is the repo if that helps answer some other questions: https://github.com/Bartekswistak/fun_guy_chef/tree/jquery
I can't confirm the rest of your code is working correctly, but you will need handle the submit event manually to prevent the page from reloading...
$("#new_comment").on("submit", function(e) {
e.preventDefault();
....
The submit event reloads the page. To stop it from reloading the page, prevent its default action. So, your very first function would look like:
$(function createComment() {
$("#new_comment").on("submit", function(e) {
e.preventDefault();
const values = {
description: $('#comment_description').val(),
rating: $('#comment_rating').val()
};
const newComment = new Comment(values);
newComment.commentConfirm();
});
});

Pebble configuration page communications not responding

I'm creating my first watchface which requires a configuration page where two strings can be stored (a title and a message).
I'm not too familiar with all the communication things because there aren't really any full on examples out there but I've tried to get as far as possible with this.
Here is the relevant code to all my spaces
main.c
static void inbox_received_callback(DictionaryIterator *iterator, void *context) {
APP_LOG(APP_LOG_LEVEL_INFO, "Message received!");
// Get the first pair
Tuple *t = dict_read_first(iterator);
//Long lived buffers
static char title_buffer[64];
static char message_buffer[124];
// Process all pairs present
while(t != NULL) {
// Process this pair's key
switch (t->key) {
case TITLE_DATA:
snprintf(title_buffer, sizeof(title_buffer), "%s", t->value->cstring);
text_layer_set_text(title_layer, title_buffer);
APP_LOG(APP_LOG_LEVEL_INFO, "TITLE_DATA received with value %d", (int)t->value->int32);
break;
case MESSAGE_DATA:
snprintf(message_buffer, sizeof(message_buffer), "%s", t->value->cstring);
text_layer_set_text(message_layer, message_buffer);
APP_LOG(APP_LOG_LEVEL_INFO, "MESSAGE_DATA received with value %d", (int)t->value->int32);
break;
}
// Get next pair, if any
t = dict_read_next(iterator);
}
}
pebbleScript.js
var title = localStorage.getItem('title') ? localStorage.getItem('title') : 'Title',
message = localStorage.getItem('message') ? localStorage.getItem('message') : "Message that can be changed in watchface 'Settings'";
Pebble.addEventListener('showConfiguration', function(e) {
console.log("Showing configuration");
// Show config page
Pebble.openURL('https://dl.dropboxusercontent.com/s/kzl44khedt5e22d/config.html?dl=0');
});
Pebble.addEventListener('webviewclosed', function(e) {
var options = JSON.parse(decodeURIComponent(e.response));
title = encodeURIComponent(options.title);
message = encodeURIComponent(options.message);
if(title == 'undefined') {
title = 'Title';
} if (message == 'undefined') {
message = "Message that can be changed in watchface 'Settings'";
}
localStorage.setItem('title', title);
localStorage.setItem('message', message);
console.log("Configuration window returned: ", JSON.stringify(options));
});
Pebble.addEventListener('ready', function(e) {
console.log("PebbleKit JS Ready!");
//Construct a dictionary
var
dict = {
'TITLE_DATA' : title,
'MESSAGE_DATA' : message
};
//Send a string to Pebble
Pebble.sendAppMessage(dict, function(e) {
console.log("Send successful.");
}, function(e) {
console.log("Send failed!");
});
});
config.html
<h3>Title:</h3>
<input type="text" name="title" id="title"></input>
<h3>Message:</h3>
<input type="text" name="message" id="message"></input>
<br>
<input type="submit" id="cancelButton" value="Cancel">
<input type="submit" id="saveButton" value="Save">
<script>
$('#cancelButton').click(function() {
location.href = 'pebblejs://close';
});
$('#saveButton').click(function() {
var options = {
title: $('title').val(),
message: $('#message').val()
}
location.href = 'pebblejs://close#' + encodeURIComponent(JSON.stringify(options));
});
function getURLVariable(name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)",
regex = new RegExp(regexS),
results = regex.exec(window.location.href);
if (results == null) return "";
else return results[1];
}
$(document).ready(function() {
var priorTitle = getURLVariable('title');
priorTitle = decodeURI(priorTitle);
if (priorTitle) {
$('#title').html(priorTitle);
}
var priorMessage = getURLVariable('message');
priorMessage = decodeURI(priorTitle);
if (priorMessage) {
$('#message').html(priorMessage);
}
});
</script>
If anyone can see why this isn't working as intended I'd much appreciate help :) Please let me know if there are any other details I should include.
I'm using CloudPebble for the development. I've done the title and message keys in settings and defined them in my main.c as well so it's not that.
A note that I should make is, in the app log it shows "TITLE_DATA received with value....." but not the "MESSAGE_DATA received...." So the problem may lie somewhere over there.
You're declaring your "long lived buffers" inside the function:
static void inbox_received_callback(DictionaryIterator *iterator, void *context) {
...
//Long lived buffers
static char title_buffer[64];
static char message_buffer[124];
...
}
If you want them to stay in scope (persist), you need to declare them up with the other globals:
static Window *s_main_window;
static char title_buffer[64];
static char message_buffer[124];

Local JSON file Update

Hi trying to update the local JSON file with new input values.
Creating a posts app which is now working on local Json file.
I have a button and a text area, and a dynamic list.
once I add some input values in textarea and submit it should get appends to li and if I add another value then it should get append to another li.
What ever new values had added it should get append to the local json file.
Here is the code what I have tried.
HTML:
<ul class='Jsonlist'></ul>
<a id='postData' href='#'>Post</a>
<textarea id="tArea"></textarea>
JS:
var Json = {"three":["red","yellow","orange"]}
var items = [];
$.each( Json, function( key, val ) {
debugger;
items.push( "<li id='" + key + "'>" + Json.three + "</li>" );
});
$('.Jsonlist').append(items);
$('#postData').click(function(){
a=$('#tArea').val();
$(".Jsonlist li").append(a);
});
Working Demo
JS fiddle:
http://jsfiddle.net/JwCm9/
What's inside?
variable to hold the items
var items;
creates <ul> for items and for each item a <li>
function make_list() {
var list = $(".Jsonlist");
list.empty();
for (var i in items) {
var value = items[i];
var li = $('<li>');
li.html(value);
list.append(li);
}
};
saving and reading from local json from/into items
function save_to_local_json() {
var items_json = JSON.stringify(items);
localStorage.setItem('items', items_json);
};
function read_from_local_json() {
var items_json = localStorage.getItem('items');
items = JSON.parse(items_json);
// If the file is empty
if (!items) {
items = [];
}
};
first time calling to these functions:
read_from_local_json();
make_list();
on click event
$('#postData').click(function () {
var text = $('#tArea').val();
items.push(text);
make_list();
save_to_local_json();
});
updated my answer:
function update_json(json_data){
localStorage.setItem('json',JSON.stringify(json_data));
}
function fetch_json(){
var json_data_local = JSON.parse(localStorage.getItem('json'));
return json_data_local;
}
function display_list(json_data){
json_data.three.forEach(function(val,key) {
$('.Jsonlist').append("<li id='" + key + "'>" + val + "</li>");
});
}
console.log(localStorage.getItem('json'));
if(localStorage.getItem('json') == ""){
var Json = {"three":["red","yellow","orange"]}
update_json(Json);
}
var Json = fetch_json();
display_list(Json);
console.log(Json);
$('#postData').click(function(){
a=$('#tArea').val();
Json.three.push(a);
update_json(Json);
$('.Jsonlist li').remove();
display_list(fetch_json());
});

Jquery: Changing a value on a page as you check and uncheck checkboxe

I have this line of code that exist in a partial view. Jquery code resides in the index page hosting the partial view
<div class="paythisamountbtn">#Html.ActionLink(T("Pay This Amount"), "InvoiceCheckout", null, new { #target = "InvoiceCheckout", #class = "amebtn" }): #String.Format("{0:C}", Model.TotalDue)</div>
I have a checkbox on every row of data. This is all within a webgrid. Here is what it looks like below
#{
var gridColumns = new List<WebGridColumn>();
gridColumns.Add(grid.Column(format: (item) =>
{
var s = "<input type=\"checkbox\" name=\"InvoiceNumber\" id=\"IN" + item.InvoiceNumber.ToString() + "\" value=\"" + item.InvoiceNumber.ToString() + "|" + item.AmountDue + "\"";
if (item.IsSelected) {
s += "checked=\"true\"";
}
s+= "/>";
return s;
}
, style: "box"));
...
...
...
}
function SetViewSelected(c) {
var s = 0;
for (i = 0; i < $("input[name='InvoiceNumber']:checked").length; i++) {
invoice_details = $("input[name='InvoiceNumber']:checked")[i].value;
invoice_amount = invoice_details.split("|")[1];
s += parseFloat(invoice_amount);
}
alert(s);
//$('.paythisamountbtn').val(s);
}
As I check and uncheck the checkboxes, I want to be able to show the total on the line below as they change. At the moment the alert(s) gets me the new total
<div class="paythisamountbtn">#Html.ActionLink(T("Pay This Amount"), "InvoiceCheckout", null, new { #target = "InvoiceCheckout", #class = "amebtn" }): #String.Format("{0:C}", Model.TotalDue)</div>
I tried doing $('.paythisamountbtn').val(s); but the totaldue does not change as I check and uncheck the check boxes.
How can I do this please?
Use .text for a div
$('.paythisamountbtn').text(s)
To update the attribute value what you must do is the following:
$('.paythisamountbtn').text(parseInt($('.paythisamountbtn').text())+5);
To update the value each time you click one of the checkboxes you could do something like this:
$('#checkbox1').change(function() {
if($(this).is(":checked")) {
UpdateValueNow();
}
});

Local Storage to hold form N pages data until final submit

My scenario: I have an application that is 9 pages long for a total of about 125 inputs of varying types and sizes (only input, textarea, radio, and selects). I'd like to use local storage to save the form values. The user can move between the pages (e.g. to review before submitting the application) so I don't want to clear the local storage until they submit the application and if they change from page to page, the form should reload its values from local storage. Once they submit the form, then I'll clear the local storage but until then, the local storage should be retained.
I found this great jquery plugin and a demo page which appears to almost do what I'm looking for - well, with two exceptions:
1) The plugin prompts the user if they want to restore their previously entered info which I'd prefer to not have (I'd rather have the data just be there). My navigational buttons at the bottom of the form are simply "Previous" and "Continue" (on the first page, it is just "Continue" and on the last page they would be "Previous" and "Submit Application").
2) The plugin will prompt the user even if there is no data to load (this would be a non-issue if I can just have it load data if there is any and skip it if there is not). For example, the very first visit to the page will prompt the user to restore previously entered data.
Here is a link to the jquery.remember-state.js used in the demo page.
=======================================================
I took the demo above and tweaked the jquery.remember-state.js to try and make it do what I need but it isn't working correctly.
Here is my (jsFiddle).
NOTE 1: the jsFiddle is meant to just show my code and is not a necessarily a working example in the jsFiddle environment. If you copy the code to your local environment, you should be able to access the console.log to see if/what gets saved to the localStorage.
NOTE 2: S.O. wants formatted code inline so I'll see what I can do to make it format correctly.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>LocalStorage and Unload State Save</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="../jQueryPlugins/RememberState/form.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<!-- use the modified jquery.remember-state.js code in the JavaScript panel instead
the script tag below is the original js file
<script src="http://shaneriley.com/jquery/remember_state/jquery.remember-state.js"></script>-->
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
(function($) {
/* jQuery form remember state plugin
Name: rememberState
Version: 1.3
Description: When called on a form element, localStorage is used to
remember the values that have been input up to the point of either
saving or unloading. (closing window, navigating away, etc.) If
localStorage isn't available, nothing is bound or stored.
The plugin looks for an element with a class of remember_state to show
a note indicating there is stored data that can be repopulated by clicking
on the anchor within the remember_state container. If the element doesn't
exist, it is created and prepended to the form.
Usage: $("form").rememberState("my_object_name");
Notes: To trigger the deletion of a form's localStorage object from
outside the plugin, trigger the reset_state event on the form element
by using $("form").trigger("reset_state");
*/
if (!window.localStorage || !window.JSON) {
if (console && console.log) {
!window.localStorage && console.log("ERROR: you browser does not support" +
" localStorage (use this polyfill https://gist.github.com/350433)");
!window.JSON&& console.log("ERROR: you browser does not support" +
" JSON (use this polyfill http://bestiejs.github.com/json3/)");
}
return $.fn.rememberState = function() { return this; };
}
var remember_state = {
name: "rememberState",
clearOnSubmit: false, //default was true;
// ****************************
/*noticeDialog: (function() {
return $("<p />", {"class": "remember_state"})
.html('Do you want to restore your previously entered info?');
})(),*/
// ****************************
ignore: null,
noticeSelector: ".remember_state",
use_ids: false,
objName: false,
clickNotice: function(e) {
var data = JSON.parse(localStorage.getItem(e.data.instance.objName)),
$f = $(this).closest("form"),
$e;
for (var i in data) {
$e = $f.find("[name=\"" + data[i].name + "\"]");
if ($e.is(":radio, :checkbox")) {
$e.filter("[value=" + data[i].value + "]").prop("checked", true);
}
else if ($e.is("select")) {
$e.find("[value=" + data[i].value + "]").prop("selected", true);
}
else {
$e.val(data[i].value);
}
$e.change();
}
e.data.instance.noticeDialog.remove();
e.preventDefault();
},
chooseStorageProp: function() {
if (this.$el.length > 1) {
if (console && console.warn) {
console.warn("WARNING: Cannot process more than one form with the same" +
" object. Attempting to use form IDs instead.");
}
this.objName = this.$el.attr("id");
}
},
errorNoID: function() {
if (console && console.log) {
console.log("ERROR: No form ID or object name. Add an ID or pass" +
" in an object name");
}
},
saveState: function(e) {
var instance = e.data.instance;
var values = instance.$el.serializeArray();
// jQuery doesn't currently support datetime-local inputs despite a
// comment by dmethvin stating the contrary:
// http://bugs.jquery.com/ticket/5667
// Manually storing input type until jQuery is patched
instance.$el.find("input[type='datetime-local']").each(function() {
var $i = $(this);
values.push({ name: $i.attr("name"), value: $i.val() });
});
values = instance.removeIgnored(values);
values.length && internals.setObject(instance.objName, values);
},
save: function() {
var instance = this;
if (!this.saveState) {
instance = this.data(remember_state.name);
}
instance.saveState({ data: { instance: instance } });
},
removeIgnored: function(values) {
if (!this.ignore) { return values; }
$.each(this.ignore, function(i, name) {
$.each(values, function(j, input) {
if (name === input.name) { delete values[j]; }
});
});
return values;
},
init: function() {
var instance = this;
// ****************************
/* if (instance.noticeDialog.length && instance.noticeDialog.jquery) {
instance.noticeDialog.find("a").bind("click." + instance.name, {
instance: instance
}, instance.clickNotice);
}*/
// ****************************
instance.chooseStorageProp();
if (!instance.objName) {
instance.errorNoID();
return;
}
if (localStorage[instance.objName]) {
// ****************************
/*if (instance.noticeDialog.length && typeof instance.noticeDialog === "object") {
instance.noticeDialog.prependTo(instance.$el);
}
else {
instance.$el.find(instance.noticeSelector).show();
}*/
// ****************************
}
if (instance.clearOnSubmit) {
instance.$el.bind("submit." + instance.name, function() {
instance.$el.trigger("reset_state");
$(window).unbind("unload." + instance.name);
});
}
instance.$el.bind("reset_state." + instance.name, function() {
localStorage.removeItem(instance.objName);
});
// ****************************
/*$(window).bind("unload." + instance.name, { instance: instance }, instance.saveState);
instance.$el.find(":reset").bind("click.remember_state", function() {
$(this).closest("form").trigger("reset_state");
});*/
}
};
var internals = {
setObject: function(key, value) { localStorage[key] = JSON.stringify(value); },
getObject: function(key) { return JSON.parse(localStorage[key]); },
createPlugin: function(plugin) {
$.fn[plugin.name] = function(opts) {
var $els = this,
method = $.isPlainObject(opts) || !opts ? "" : opts;
if (method && plugin[method]) {
plugin[method].apply($els, Array.prototype.slice.call(arguments, 1));
}
else if (!method) {
$els.each(function(i) {
var plugin_instance = $.extend(true, {
$el: $els.eq(i)
}, plugin, opts);
$els.eq(i).data(plugin.name, plugin_instance);
plugin_instance.init();
});
}
else {
$.error('Method ' + method + ' does not exist on jQuery.' + plugin.name);
}
return $els;
};
}
};
internals.createPlugin(remember_state);
})(jQuery);
});//]]>
</script>
<script>
var thisPage = 'page1'; //defines the variable to use for local storage
$(function() {
$("form")
.rememberState({objName: thisPage})
.submit(function() {localStorage.setItem(thisPage, $(this).serializeArray());
return true;
});
});
</script>
</head>
<body>
<form method="post" action="page2.cfm">
<fieldset>
<dl>
<dt><label for="first_name">First Name</label></dt>
<dd><input type="text" name="first_name" id="first_name" /></dd>
<dt><label for="last_name">Last Name</label></dt>
<dd><input type="text" name="last_name" id="last_name" /></dd>
</dl>
</fieldset>
<fieldset class="actions">
<input type="submit" value="Continue" />
</fieldset>
</form>
</body>
</html>
I thought this was going to be tougher than it was. Here is the solution I came up with:
On the form page when the submit button is pressed:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var thisPageID = 'page1'; // each page gets its own
$('form').submit(function() {
var formFields = $(this).serialize();
localStorage.setItem(thisPageID, formFields);
data = localStorage.getItem(thisPageID);
return true;
});
});
</script>
Then on the final page, I retrieve the data for each page by its page id from the local storage and populate my div tags with the data.
function getLocalData(id){
var ApplicantData;
ApplicantData = localStorage.getItem(id);
if (ApplicantData){
$.each(ApplicantData.split('&'), function (index, elem) {
var vals = elem.split('=');
var $div = $("#"+vals[0]);
var separator = '';
// console.log($div);
if ($div.html().length > 0) {
separator = ', ';
}
$div.html($div.html() + separator + decodeURIComponent(vals[1].replace(/\+/g, ' ')));
});
}
}
Some of the Articles that helped me (some SO, some external):
- Clear localStorage
- http://www.simonbingham.me.uk/index.cfm/main/post/uuid/using-html5-local-storage-and-jquery-to-persist-form-data-47
- http://www.thomashardy.me.uk/using-html5-localstorage-on-a-form
There were more but this is all I still had open in tabs.

Categories