How to clear a new record from ember.js frontend after it fails Rails validation (422 error)? - ruby-on-rails

I'm working on a basic reddit clone app with Rails and ember.js (via the ember-rails gem). Basically I have a 'post' model/controller in Rails which works correctly, but when I add a new post from the ember post model's create action, even if it fails the Rails validation, if I then go to the 'posts' index page which lists all the posts, I can see it there (i.e. ember is keeping the data). When I refresh it goes away, but I'm wondering what is the best way to purge that data so that it gets deleted upon rejection from the backend? Another odd thing is that simply going to the posts/new page at all creates a new blank post which is then visible on the Then on the client-side, I have the following files in app/assets/javascripts/routes:
posts_route.js:
RedditJp.PostsRoute = Ember.Route.extend({
model: function() {
return this.get('store').find('post');
}
});
posts_new_route.js:
RedditJp.PostsNewRoute = Ember.Route.extend({
model: function(){
return this.get('store').createRecord('post'); },
actions: {
create: function() {
var newPost = this.get('currentModel');
var self = this;
newPost.save().then(
function() { self.transitionTo('posts'); },
function() { }
);
}
}
});
Here's the form I'm trying to use to submit the data in posts/new.hbs:
<h1> Add a post </h1>
{{#each error in errors.title}}
<p>{{error.message}}</p>
{{/each}}
<form {{action "create" on="submit"}}>
<div>
<label>
Title<br/>
{{input type="text" value=title}}
</label>
</div>
<div>
<label>
Address<br/>
{{input type="text" value=address}}
</label>
</div>
<div>
<label>
Vote count<br/>
{{input type="text" value=voteCount}}
</label>
</div>
<button>Save</button>
</form>
and then in assets/javascripts/templates/posts/ I have index.hbs:
<h1>Posts</h1>
<ul>
{{#each}}
<li>{{title}} at {{address}} vote count: {{voteCount}}</li>
{{else}}
<li>There are no posts.</li>
{{/each}}
</ul>
and here's my router.js:
RedditJp.Router.map(function() {
this.resource('posts', function() {
this.route('new')
});
this.resource('home', function() {
});
});
RedditJp.IndexRoute = Ember.Route.extend({
redirect: function(){
this.transitionTo('home')
}
});
I was thinking I could just add a check in the posts/index.hbs file and only show records that aren't dirty, but there must be a cleaner way of doing it, so I'm wondering what would be considered best practice in this case (I'm thinking there should be some code I could add to the promise in posts_new_route.js to deal with this, but I can't quite figure it out).
Thanks a lot! And let me know if you need any additional info.

You can check if model isNew in template to hide new Record ( also you can use isEmpty property )
var record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
In template will look like {{each model}}
{{#if model.get('isNew')}}
record.save().then(function(){
// Success callback
}, function() {
model..deleteRecord();
});

Related

Live search MVC

I'm looking for live search for ASP.NET and entity framework. I'm a little bit green with it. I read that it needs to use ajax, but I never used it before and can't get good example. Here is a piece of code, cshtml (part of textbox)
<div class="form-horizontal">
<hr />
<h4>Search for a client: </h4>
<div class="input-group">
<span class="input-group-addon" id="Name">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</span>
#Html.TextBox("Name", "", new { #class = "form-control", placeholder = "Name" })
</div>
<div><h6></h6></div>
<div class="input-group">
<span class="input-group-addon" id="Surname">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</span>
#Html.TextBox("Surname", "", new { #class = "form-control", placeholder = "Surname" })
</div>
<div><h6></h6></div>
<button type="submit" class="btn btn-default" data-toggle="modal" data-target="#infoModal">Search</button>
</div>
this is a part of controller:
public ActionResult Index(string Name, string Surname)
{
var SearchList = from m in db.Klienci
select m;
if (!String.IsNullOrEmpty(Name))
{
SearchList = SearchList.Where(s => s.Name.Contains(Name));
}
if (!String.IsNullOrEmpty(Surname))
{
SearchList = SearchList.Where(s => s.Nazwisko.Contains(Surname));
}
return View(SearchList);
}
So it search for me clients by name and surname, but it refresh full page when it lost focus or after clicking the button. How to solve it, to get live search? after each keystroke search through database? I'm a little bit green, would you Help me?
You can listen to the keyup event on your input element, read the value and send it to the server using ajax. Return the results and in the ajax call's success callback, update the ui with the results.
$(function() {
$("#Name,#SurName").keyup(function(e) {
var n = $("#Name").val();
var sn = $("#SurName").val();
$.get("/Home/Index?Name="+n+"&SurName="+sn,function(r){
//update ui with results
$("#resultsTable").html(r);
});
});
});
The code basically listens to the key up event on the two input textboxes and read the values and send to the /Home/Index action method using jquery get method asynchronously.When the action method returns the response, we update the DOM.
Assuming resultsTable is the Id of the table where we list the results.
Also, since you are returning the partial view result ( without layout headers), you should use return PartialView() instead of return View()
if(Request.IsAjaxRequest())
return PartialView(SearchList);
return View(SearchList);
Here is nice example/tutorial how to use Ajax with ASP.NET MVC
http://www.itorian.com/2013/02/jquery-ajax-get-and-post-calls-to.html
EDITED: 2016-07-20
Example:
$(function () {
$("searchField").keyup(function () {
$.ajax({
type: "POST",
url: "/Controller/Action",
data: data,
datatype: "html",
success: function (data) {
$('#result').html(data);
}
});
});
You have to visit the server to get data from server and without ajax it is not possible. Now the question is how to make ajax call, you can use jQuery js lib to do but I would recommend you to try angular as data binding in angular will fulfill your needs.
Take a look at followings links
Angular Ajax Service -
jQuery Ajax

Second time partialview not loading to div via from .ajax() in MVC4

I have issue loading partialview to div second time. I have checked previous posts in SO but non of them really helped me. So I am posting my issue here.
index.cshtml
<div id="DivEmailContainer" style="display:block" class="row">
</div>
_EditEmail.cshtml
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-2 ">
<input type="submit" value="Save" class="btn btn-success width100per" />
</div>
script type="text/javascript">
$(function () {
$("#frmEmail").validate({
rules: {
...
submitHandler: function (form) {
$.ajax({
url: 'PostEditEmail',
type: 'Post',
data: $(form).serialize(),
success: function (result) {
alert("In success");
$('#DivEmailContainer').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
},
complete: function (xhr, textStatus) {
alert(xhr.responseText);
alert(textStatus);
}
});
}
});
controller
public PartialViewResult PostEditEmail(string actiontype, FormCollection col)
{
var communicationLocation = string.Empty;
....
return PartialView("_EditEmail", memberemail);
}
First time partialview loading into DivEmailContainer to error. If submit again partialview loading full post back. not even it is calling submitHandler.
Only thing I observed is 1st time submit <form post was /ContactInformation/GetEditEmailbut when I submit second time <form post was /ContactInformation/PostEditEmail.
What could be wrong?
update
second time Forloop scriptblock loading. May be it is issue with Forloop?
#using (Html.BeginScriptContext())
{
Html.AddScriptBlock(
update
issue with forloop htmlhelper, not with ajax. secondtime script is not loading. #Russ Cam can help on this.
from my experience putting script in a partial leads to very inconsistent results. expecially with the script being inserted into the middle of the page. I would highly recommend that you pull your script from the partial and put it on the main page. Since the partial is loaded after the page load you will need to tie the script to the partial one of 2 ways.
1. tie the events to the document
$(document).on('click', '.targetClass', function(){
//do stuff
});
for example to put an id on your input and change it to a button
<input type="button" value="Save" id="btnSave" class="btn btn-success width100per" />
your click event would then be
$(document).on('click', '#btnSave', function(){
//your ajax call here
});
being tied to the document this click event would fire even though the input is inserted into the document after load
put the script in a function that is called after the partial is loaded
change your
$(function () {
to
function partialScript(){
and call this function after the partial is loaded
$('#DivEmailContainer').html(result);
partialScript();
Try to load partial view like this
$("#DivEmailContainer").load('#Url.Action('ActionName', 'ControllerName')', function () {
//Perform some operation if you want after load.
});

angularJS with MVC call - how to do something other than CRUD?

I've been following web tutorials to try to learn angularJS on a .NET MVC Application. All the tutorials seem to cover getting a list, getting an individual item etc.
What I want to do is allow the user to fill in an email address, I want to verify that email address against the database and return true or false if it existed. I'm then trying to put that value in the scope so I can do something in response to whether its true or false.
I'm using a single page app so this is the login html.
<form name="form" class="form-horizontal">
<div class="control-group" ng-class="{error: form.ValidEmailAddress.$invalid}">
<label class="control-label" for="ValidEmailAddress">Valid Email Address</label>
<div class="controls">
<input type="email" ng-model="item.ValidEmailAddress" id="ValidEmailAddress">
</div>
</div>
<div class="form-actions">
<button ng-click="login()" class="btn btn-primary">
Go!
</button>
<label ng-if="user.isAuthorised">Authorised</label>
<label ng-if="!user.isAuthorised">NotAuthorised</label>
</div>
</form>
In my app.js file I declare a loginCtrl controller when the url was /login so that's all fine. The logic that I'm calling on my button click is this:
var LoginCtrl = function ($scope, $location, $http, AuthorisedUser) {
$scope.login = function() {
var isValidUser = $http.get("/AuthorisedUser/IsValidUser/" + $scope.item.ValidEmailAddress);
$scope.user.isAuthorised = isValidUser;
} };
Which is then calling an MVC AuthorisedUserController class method:
public bool IsValidUser(string id)
{
var list = ((IObjectContextAdapter)db).ObjectContext.CreateObjectSet<ApprovedUser>();
var anyItems = list.Any(u => u.ValidEmailAddress == id);
return anyItems;
}
So it vaguely seemed to be working when I put in a value like "aaa" into the textbox. But as soon I try putting in an email address the value is undefined. Maybe I'm supposed to be doing a post but the only thing I can successfully hit my .NET controller with is by using get.
I'm sure I'm missing fundamental knowledge and potentially tackling this in the wrong way.
In case it helps I've created a module and defined factories like this:
var EventsCalendarApp = angular.module("EventsCalendarApp", ["ngRoute", "ngResource"]).
config(function ($routeProvider) {
$routeProvider.
when('/login', { controller: LoginCtrl, templateUrl: 'login.html', login: true }).
otherwise({ redirectTo: '/' });
});
EventsCalendarApp.factory('AuthorisedUser', function ($resource) {
return $resource('/api/AuthorisedUser/:id', { id: '#id' }, { isValidUser: { method: 'GET' } });
});
One of my questions is - should I be accessing the controller method using the $http object, or is there a way of using my factory declaration so that I can go something like:
AuthorisedUser.IsValidUser($scope.item.validEmailAddress)
I know in the tutorial I was following I could do stuff like:
CalendarEvent.save()
to be able to call a CalendarEventController post method.
What i think is, your get() function will return a promise. and you can't assign promise like this. so better try this approch once. I hope, it'd work. if not please let me know...
here I assume your first,second and third snippet of code works fine...
$http.get("/AuthorisedUser/IsValidUser/" + $scope.item.ValidEmailAddress).success(function (result, status) {
var isValidUser=result;
$scope.user.isAuthorised = isValidUser;
$scope.$apply();
}).error(function (result, status) {
//put some error msg
});

add item to observable array in viewmodel from another partial view (MVC)

I am new to knockoutJS. I am working on an MVC application where I want to implement knockoutJS but the scenario is bit different.
I have a page where I am showing a list. I have 3 links on the page and on click of them I am adding partial views to page accordingly. What I want to do is that whenever I add values/data to partial views, the list which is on page should be updated with knockout. In other words I want to add value to observable array when I save data from partial view.
Please let me know if this is possible or I should keep it in jquery only.
Here is the code:
Main view:
<input type="button" value="Add Partial View" onclick="LoadPartial();" />
<div id="dvContent"></div>
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: name"> </span>
Remove
</li>
</ul>
<button data-bind="click: addPerson">Add</button>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/knockout-2.1.0.js"></script>
<script>
function LoadPartial() {
$.ajax({
url: "/home/index",
dataType:"html",
type: "GET",
success: function (data) {
$("#dvContent").html(data);
}
});
}
</script>
<script>
function AppViewModel() {
var self = this;
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
self.addPerson = function () {
self.people.push({ name: "New at " + new Date() });
};
self.removePerson = function () {
self.people.remove(this);
}
}
ko.applyBindings(new AppViewModel());
</script>
Partial View:
<table>
<tr>
<td>Add new Row</td>
<td><input type="button" value="Add" data-bind="click: addPerson"/></td>
</tr>
</table>
Thanks,
JsHunjan
It is easy to accomplish with Knockout. You need to show some code that you have tried though if you want to get some help. I will post a general answer but it isn't going to fix your use case exactly, just basically -
Create an object to hold your new item, you can do this either in the parent or the child view model, but if you do it in the child you need to pass it back to the parent.
Once you hit a save button or add or whatever in the child view model just do a .push() into the observableArray that you created ex... - myObservableArray.push(newItem());
Knockout will recognize all of the changes taking place and perform the actions you want automatically.
Hope this helps.

Multiple ViewModels with Knockout and ASP.NET MVC4 SPA

I'm new to ASP.NET MVC SPA and Knockout.js os maybe it's a simple mistake I made...
Situation: I have two partialviews in my website and I want that every partialview has his own Knockout ViewModel so I won't get a huge ViewModel.
My current ViewModel:
/// <reference path="../_references.js" />
function MobileDeliveriesViewModel() {
var self = this;
// Data
self.currentDelivery = ko.observable();
self.nav = new NavHistory({
params: { view: 'deliveries', deliveryId: null }
});
// Test
self.foo = "FooBar"
self.bar = "BarFoo"
self.nav.initialize({ linkToUrl: true });
// Navigate Operations
self.showDeliveries = function () { self.nav.navigate({ view: 'deliveries' }) }
self.showCustomers = function () { self.nav.navigate({ view: 'customers' }) }
}
function BarFooViewModel() {
var self = this
//MobileDeliveriesViewModel.call(self)
self.bar2 = "BarFooTwo"
}
ko.applyBindings(new MobileDeliveriesViewModel());
ko.applyBindings(new MobileDeliveriesViewModel(), $('#BarFoo')[0]);
ko.applyBindings(new BarFooViewModel(), document.getElementById('BarFoo'));
My Index.cshtml:
<div data-bind="if: nav.params().view == 'deliveries'">
#Html.Partial("_DeliveriesList")
</div>
<div class="BarFoo" data-bind="if: nav.params().view == 'customers'">
#Html.Partial("_CustomersList")
</div>
<script src="~/Scripts/App/DeliveriesViewModel.js" type="text/javascript"></script>
My CustomerPartialView:
<div id="BarFoo" class="content">
<p data-bind="text: bar"></p>
<p data-bind="text: bar2"></p>
<button data-bind="click: showDeliveries, css: { active: nav.params().view == 'deliveries' }">Deliveries</button>
</div>
My DeliveriesPartialView:
<div class="content">
<p data-bind="text: foo"></p>
<button data-bind="click: showCustomers, css: { active: nav.params().view == 'customers' }">Customers</button>
</div>
If I run this, it won't recognize the bar2 propertie in my BarFooViewModel...
I have tried 2 different applyBindings at the end of my ViewModel.
Anybody got an idea or is their a better way/pattern to do this?
are there JS errors on page?
nav.params().view
but params: { view: 'deliveries', deliveryId: null } - it's not function.
and if you want use a few view models on single page - check this http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+KnockMeOut+%28Knock+Me+Out%29 acticle. you have to use "stopBinding"
It looks like you are applying multiple data bindings to the same sections.
ko.applyBindings(new MobileDeliveriesViewModel();
This will bind to all elements one the page.
ko.applyBindings(new MobileDeliveriesViewModel(), $('#BarFoo')[0]);
this will try to bind to all elements inside the div
ko.applyBindings(new BarFooViewModel(), document.getElementById('BarFoo'));
This will also try to bind to all elements inside the div.
To keep things simple, you should try to bind a single view model to a single html section. I've found that trying to bind two view models in the same html section has been hard to get work correctly and trouble shoot.
Jack128's answer also makes some good points.

Resources