KnockoutMvc tuorial of helloworld not working - knockout-mvc

I am following this tutorial for knockoutmvc. Following is my code.
View : cshtml
#using PerpetuumSoft.Knockout
#model DynamicRowAdd.Models.HelloWorldModel
#{
var ko = Html.CreateKnockoutContext();
}
#{
ViewBag.Title = "View";
}
<h2>View</h2>
<p>First name: #ko.Html.TextBox(Model1=>Model1.FirstName)</p>
<p>Last name: #ko.Html.TextBox(Model1=>Model1.LastName)</p>
<h2>Hello, #ko.Html.Span(Model1=>Model1.FullName)!</h2>
#ko.Apply(Model)
Model :
using DelegateDecompiler;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace DynamicRowAdd.Models
{
public class HelloWorldModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
[Computed]
[ScriptIgnore]
[JsonIgnore]
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
}
Controller :
using DynamicRowAdd.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PerpetuumSoft.Knockout;
namespace DynamicRowAdd.Controllers
{
public class HelloWorldController : Controller
{
// GET: HelloWorld
public ActionResult Index()
{
return View(new HelloWorldModel
{
FirstName = "Steve",
LastName = "Sanderson"
});
}
}
}
Here, when i run the code I should get the output such as the output mentioned in the tutorial. But I am not getting output as it is there in the tutorial. Instead I am getting blank in firstname, lastname and fullname.
What possibly I am doing wrong.?

The examples are missing one key part of the setup: you have to include the necessary javascript files in your layout/view in order to Knockout and knockoutmvc work correctly.
This is described in the QuickStart section
Add links to next js-files:
<script src="#Url.Content("~/Scripts/jquery-x.y.z.min.js")" type="text/javascript"></script> <!-- Use your version of jQuery -->
<script src="#Url.Content("~/Scripts/knockout-x.y.z.js")" type="text/javascript"></script> <!-- Use your version of knockout -->
<script src="#Url.Content("~/Scripts/knockout.mapping-latest.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/perpetuum.knockout.js")" type="text/javascript"></script>

Related

'Specified cast is not valid' when I reload listview items - Xamarin Forms

I'm trying to make an app that saves subjects into an SQLite database and I'm facing an exception: 'Specified cast is not valid'. That happens when I reload the listview items.
(SubjectViewModel.UpdateSubjects())
I receive the data from SubjectServices static class, with async connection.
I set the contentpage binding context to this viewmodel and then set the listview itemssource's binding the SubjectViewModel's SubjectList.
XAML code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:resx="clr-namespace:MyApp.Resources"
x:Class="MyApp.View.ShellPages.SubjectsPage">
<ContentPage.ToolbarItems>
<ToolbarItem Text="{x:Static resx:AppResources.NewSubject}"
Command="{Binding SubjectNewSCommand}"/>
</ContentPage.ToolbarItems>
<ContentPage.Content>
<ListView x:Name="subjectListView" ItemsSource="{Binding SubjectList}"
IsRefreshing="True" RefreshCommand="{Binding SubjectRefreshCommand}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" Detail="{Binding AddedTime, StringFormat='{0:d}'}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
</ContentPage>
SubjectViewModel:
using MyApp.Model;
using MyApp.View.ShellPages;
using MyApp.ViewModel.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
namespace MyApp.ViewModel
{
public class SubjectViewModel
{
public ObservableCollection<Subject> SubjectList { get; set; }
public SubjectPageRefreshCommand SubjectRefreshCommand { get; set; }
public SubjectNewSubjectCommand SubjectNewSCommand { get; set; }
public SubjectViewModel()
{
SubjectRefreshCommand = new SubjectPageRefreshCommand(this);
SubjectNewSCommand = new SubjectNewSubjectCommand(this);
SubjectList = new ObservableCollection<Subject>();
}
public async void UpdateSubjects()
{
var subjectList = await SubjectServices.GetSubjects();
SubjectList.Clear();
foreach (var subject in subjectList)
SubjectList.Add(subject);
}
public async void Navigate()
{
await App.Current.MainPage.Navigation.PushAsync(new NewSubjectPage());
}
}
}
Subject class:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using SQLite;
namespace MyApp.Model
{
public class Subject
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[MaxLength(50)]
public string Name { get; set; }
public DateTime AddedTime { get; set; }
}
}
What could be the problem? I've tried to find any solution but didn't succeed.
I appreciate any kind of help.

Entity Framework Core 3 : Type must match overridden member

I have the following two dbcontexts in my Entity Framework Core solution. The OrganisationContext derives from SagitarriContext. I am overiding the base property DbSet<Person> Person. I am getting the following error in the derived class:
Error CS1715
'OrganisationContext.Person': type must be 'DbSet' to match overridden member 'SagitarriContext.Person'
DbContext
namespace Genistar.Data.DbContexts.Interfaces
{
public class SagitarriContext : DbContext, ISagitarriContext
{
public SagitarriContext();
public SagitarriContext(DbContextOptions<SagitarriContext> options);
protected SagitarriContext(DbContextOptions options);
public virtual DbSet<Person> Person { get; set; }
}
}
namespace Genistar.Data.DbContexts
{
public class OrganisationContext : SagitarriContext
{
private readonly ITimeProvider _timeProvider;
private readonly IUserContextResolverFactory _userContextResolver;
public OrganisationContext(DbContextOptions options)
: base(options)
{
}
public OrganisationContext(DbContextOptions options, ITimeProvider timeProvider, IUserContextResolverFactory userContextResolver)
: base(options)
{
_timeProvider = timeProvider;
_userContextResolver = userContextResolver;
}
public override DbSet<Person> Person { get; set; }
}
}
namespace Genistar.Data.DbContexts.Interfaces
{
public interface ISagitarriContext
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
DbSet<TQuery> Set<TQuery>() where TQuery : class;
public DatabaseFacade Database { get; }
DbSet<Person> Person { get; set; }
}
}
Usings
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Genistar.Data.DbContexts;
using Genistar.Data.Models;
using Genistar.Organisation.Models.Representative;
using Genistar.Organisation.Models.Unregistered;
using Genistar.Organisation.Models.User;
using Person = Genistar.Organisation.Models.DataModels.Person;
using PersonNote = Genistar.Organisation.Models.DataModels.PersonNote;
using Genistar.Security.Context;
using Genistar.Security.Utility;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
You are not in the same namespace, so the Person class used in DbSet<Person> might be a different one in Genistar.Data.DbContexts.Interfaces and Genistar.Data.DbContexts. Also, we don't see the usings, so there might be an error there.

Invalid Column name error in MVC 4

I have created a simple class and a list based on this class. When i try to populte this list and send to view iam getting an error. Please view my class and custom mapper model based on database.
Folloiwng is the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcModal.Models
{
public class mytransaction
{
public int Id { get; set; }
public int my_trn_id { get; set; }
public string Description { get; set; }
public List<mytransaction> Translist { get; set; }
}
}
Following is the custom database mapper class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using MvcModal.Models;
namespace MvcModal.Models
{
public class PrContext : DbContext
{
static string _conString = #"Data Source=.\sqlexpress;Initial Catalog=MyDb;Integrated Security=True";
public PrContext() : base(_conString) { }
public DbSet<mytransaction> MyTransactions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<PrContext>(null);
modelBuilder.Configurations.Add(new NewTransactMapper());
}
public class NewTransactMapper : EntityTypeConfiguration<mytransaction>
{
public NewTransactMapper()
{
this.ToTable("mytransaction");
this.Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasKey(m => m.my_trn_id);
}
}
}
}
Following is the error image.
Please view the red circuled error and see the mytransactions_my_trn_id text. mytransaction is my table name and my_trn_id is my column name. Rest of the columns have no issue, but this making me insane.
Please anyone guide what iam missing and how can i make my table name and column isolate and resolve this error. Thanks in advance.
If you want to create the model you have to know wich columns EF generates to handle relationships and if you don't specify the names (as in this case) you have to know wich name EF will assign to properties.
I suggest you (I do this) to generate the model on an empty database with EF standard migrations then copy the structure from the EF created database.
In your case you only need to add the column mytransaction_my_trn_id of type int (same as id). If you need the same database the EF would generate with migrations, you need also to add an index on that column and a relationship from that column to my_trn_id column (primary key).
I have done it using the following code. It may also be help someone. Also thanks to everyone for their nice suggestions.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using payorder_draft_printing.Controllers;
namespace payorder_draft_printing.Models
{
public class context_db : DbContext
{
static string _conString = #"Data Source=my datasource";
public context_db()
: base(_conString)
{
Database.SetInitializer<context_db>(null);
}
public IDbSet<sms_description> sms_description { get; set; }
public IDbSet<sms_imported_trn_code> sms_imported_trn_code { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new sms_description_mapper());
modelBuilder.Configurations.Add(new sms_imported_trn_code_mapper());
}
}
class sms_description_mapper : EntityTypeConfiguration<sms_description>
{
public sms_description_mapper()
{
ToTable("dbo.sms_description");
this.Property(x => x.id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasKey(x => x.trn_code);
Property(x => x.trn_code).HasColumnName("trn_code").IsRequired();
}
}
class sms_imported_trn_code_mapper : EntityTypeConfiguration<sms_imported_trn_code>
{
public sms_imported_trn_code_mapper()
{
ToTable("dbo.sms_imported_trn_code");
HasKey(x => x.trn_code);
this.Property(x => x.id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.trn_code).HasColumnName("trn_code").IsRequired();
}
}
}

Adding WebApi to an existing MVC4 app that uses Entity framework

I've been going around with this for a few days now. I have an existing MVC 4 project that uses entity framework for database creation. The app works as intended but I have a new requirement to add web api to this site. This is a database of quotes and the requirement is to return a simple quote that only contains limited information of the full database entry.
My original model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Exercise4.Models
{
public class Quote
{
public int QuoteID { get; set; }
[Required (ErrorMessage = "A Category Field Must be selected or a New one must be Created before continuing")]
public int CategoryID { get; set; }
[Display (Name="Quotation")]
[Required (ErrorMessage = "A Quotation is Required")]
public string QName { get; set; }
[Display (Name= "Author")]
[Required (ErrorMessage = "An Authors Name is Required\n Use 'Unknown' if needed")]
public string QAuthor { get; set; }
[Display (Name = "Category")]
public virtual Category category { get; set; }
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime Date { get; set; }
public int UserId { get; set; }
}
}
The Simple Quote Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Exercise4.Models
{
public class SimpleQuote
{
public int Id { get; set; }
public string Quote { get; set; }
public string Author { get; set; }
public string Category { get; set; }
}
}
The Context (*Note the SimpleQuote entry was added automagicly when I scaffold the new QuoteApiController)
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Exercise4.Models
{
public class QuoteContext : DbContext
{
public DbSet<Quote> Quotes { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<UserProfile> UserIds { get; set; }
public QuoteContext()
{
Configuration.ProxyCreationEnabled = false;
}
public DbSet<SimpleQuote> SimpleQuotes { get; set; }
}
}
This returns an error when accessing the /api/quoteapi/ page with
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
Obviously this error occurs because it is trying to return a SimpleQuote Object that doesn't exist in the database.
The API Controller that was created.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Exercise4.Models;
namespace Exercise4.Controllers
{
public class QuoteApiController : ApiController
{
private QuoteContext db = new QuoteContext();
// GET api/QuoteApi
public IEnumerable<SimpleQuote> GetSimpleQuotes()
{
return db.SimpleQuotes.AsEnumerable();
}
// GET api/QuoteApi/5
public SimpleQuote GetSimpleQuote(int id)
{
SimpleQuote simplequote = db.SimpleQuotes.Find(id);
if (simplequote == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return simplequote;
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
Where am I going awry. I can't return a model that doesn't exist in the database. If I change the call in the api to return a Quote model that works but I only need to return the quote, author and category as strings. Would I just return the Quote object in the controller, pull out the information I need and then return the SimpleQuote object? Not sure how to do that. Any suggestions?
You mentioned scaffolding, are you using Code First to create your Database?
Also you only want the SimpleQuote for returning the information, it looks like its added to your DB context as a table. When what you really want is to pull the data from the Quote Table and build or extract the information you want and return just that. If you don’t have to return a SimpleQuote Object and just return a string you could write something very simplistic like this.
public HttpResponseMessage GetSimpleQuote(int id)
{
var quote = db.Quotes.Find(id);
if (quote == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
var output += "ID: " + quote.Id + " Quote: " + quote.Quote + " Author: " + quote.Author + " Category: " + quote.Category ;
var response = new HttpResponseMessage();
response.Content = new StringContent(output);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return response;
}
I 1+ and Accepted #CHammond's response for putting me on the right track. I do need to return a SimpleQuote object. Here is the code I used.
public SimpleQuote GetSimpleQuote(int id)
{
var quote = db.Quotes.Find(id);
if (quote == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
SimpleQuote output = new SimpleQuote();
output.Quote = quote.QName;
output.Author = quote.QAuthor;
output.Category = db.Categories.Find(quote.CategoryID).CatName;
return output;
}

Error comes as a {"Invalid object name 'dbo.TableName'."}

I'm using Entity Framework and MVC3,
I have used Model First approch...
I have used Company as a Base class and I have inherited the Lead Class from it.
When I run the application its gives an error...
This is Base Class
using System;
using System.Collections.Generic;
namespace CRMEntities
{
public partial class Company
{
public int Id { get; set; }
}
}
This is Lead Class (Child)
using System;
using System.Collections.Generic;
namespace CRMEntities
{
public partial class Lead : Company
{
public Lead()
{
this.Status = 1;
this.IsQualified = false;
}
public Nullable<short> Status { get; set; }
public Nullable<bool> IsQualified { get; set; }
}
}
I have added the controller,and in index view I have added this code...
public class Default1Controller : Controller
{
private CRMWebContainer db = new CRMWebContainer();
//
// GET: /Default1/
public ViewResult Index()
{
return View(db.Companies.OfType<Lead>().ToList());
}
}
This is DB and Model ...
Its giving the inner error -
{"An error occurred while executing the command definition. See the
inner exception for details."} {"Invalid object name
'dbo.Companies'."}
Do you have a Companies table or Company table in your database. It looks like you have a Mapping issue. Entity Framework will make some guesses as to how it pluralizes entity names by default.