Why is my code doing nothing? - html

When I run the debugger, I get 0 errors, the layout loads, and "Movies" shows up but literally nothing else. I'm fairly new to MVC and some input would be appreciated. The code for the View, Model, and Controller are below. The database contains over 100 items and a list a links is intended to appear but its just white space instead.
View:
#model IEnumerable<MyWebPage.Models.Movie>
<h1>Movies</h1>
<ul>
#foreach (var item in Model.OrderBy(x => x.Name))
{
<li>#Html.ActionLink(item.Name, "Movies", new { id = item.ID })</li>
}
</ul>
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyWebPage.Models;
namespace MyWebPage.Controllers
{
public class HomeController : Controller
{
private MoviesDbContext db = new MoviesDbContext();
public ActionResult Index()
{
return View(db.Movies.ToList());
}
public ViewResult Movies(int id)
{
Movie moviesdb = db.Movie.Find(id);
return View(moviesdb);
}
}
}
Model:
using System;
using System.Data.Entity;
namespace MyWebPage.Models
{
public class Movie
{
public int ID { get; set; }
public string Name { get; set; }
public string Cover { get; set; }
}
public class MoviesDbContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
Thanks in advance!

Related

System.Text.Json.Deserialize an array into C# class

First off, I am working with the Google recaptcha RESTful service trying to get the JSON object into a class. With WSDL's, Visual Studio will generate all this code for you so that it is easy to work with, but RESTful it seems you have to do everything yourself, am I missing something? I am working with VS2019 and would have thought there is some way to import this stuff to make life easy. I have yet to find anything, so...
Google is returning:
{
"success": false,
"error-codes": [
"invalid-input-response",
"invalid-input-secret"
]
}
I would like to deserialize it into this:
[DataContract]
public class GoogleReCaptchaResponse
{
[DataMember(Name = "success")]
public bool Success { get; set; }
[DataMember(Name = "error-codes")]
public List<string> ErrorCodes { get; set; }
[JsonExtensionData]
public Dictionary<string, object> ExtensionData { get; set; }
}
I see the error-codes in the ExtensionData, but ErrorCodes is always null. What do I have wrong?
https://dotnetfiddle.net/RtjbwR
You should use JsonPropertyName attribute from System.Text.Json.Serialization namespace
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class GoogleReCaptchaResponse
{
[JsonPropertyName("success")]
public bool Success { get; set; }
[JsonPropertyName("error-codes")]
public List<string> ErrorCodes { get; set; }
}
public class Program
{
public static void Main()
{
GoogleReCaptchaResponse json = System.Text.Json.JsonSerializer.Deserialize<GoogleReCaptchaResponse>("{ \"success\": false, \"error-codes\": [\"invalid-input-response\",\"invalid-input-secret\"]}");
if (json.ErrorCodes == null)
{
Console.WriteLine("no Error Codes");
}
else
{
Console.WriteLine("Error Codes!");
}
}
}

Cannot deserialize - JSON.NET - Xamarin

I'm struggling with below message. Other JSON objects in the same app work correctly.
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type 'Monkeys.Models.Rootobject' because the type requires a JSON
object (e.g. {"name":"value"}) to deserialize correctly.
I have the following output from the API via web browser:
[{"Id":"1","Name":"Monkey 1","Location":null,"Details":null,"SKU":null,"Size":null,
"Color":null,"Image":null,"Brand":null,"NameSort":"M"},{"Id":"2","Name":"Monkey 2",
"Location":null, "Details":null,"SKU":null,"Size":null,"Color":null,"Image":null,
"Brand":null,"NameSort":"M"}]
The Model in my App:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Monkeys.Models
{
public class Monkey
{
public string Id { get; set; }
public string Name {get;set;}
public string Location { get; set; }
public string Details { get; set; }
//URL for our monkey image!
public string SKU { get; set; }
public string Size { get; set; }
public string Color { get; set; }
public string Image { get; set; }
public string Brand { get; set; }
public string NameSort
{
get
{
if (string.IsNullOrWhiteSpace(Name) || Name.Length == 0)
return "?";
return Name[0].ToString().ToUpper();
}
}
}
public class Rootobject
{
public Monkey[] monkeys { get; set; }
}
}
The App:
using System;
using System.Net;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Monkeys.Models;
using System.Collections.Generic;
namespace Monkeys.Apis
{
public class GetMonkeys
{
public GetMonkeys()
{
}
public async Task<Monkey[]> GetMonkeysAsync()
{
var client = new System.Net.Http.HttpClient();
client.BaseAddress =
new Uri("https://microsoft- apiappce13ac35390d40a684dd6ab72a9eef8f.azurewebsites.net:443/");
var response = await client.GetAsync("api/Monkey");
var earthquakesJson = response.Content.ReadAsStringAsync().Result;
var rootobject = JsonConvert.DeserializeObject<Rootobject> (earthquakesJson);
return rootobject.monkeys;
}
}
}
Your json data is an array of Monkey. Try this
// monkeys will be a List<Monkey>
var monkeys = JsonConvert.DeserializeObject<List<Monkey>>(earthquakesJson);

WP8 No Such a table Sqlite

i m trying to develop windows phone application but i have a problem about sqlite. I couldn't connect database and app. I had error message like this "no such table: hastalik". If some 1 have any idea, please share. Thanks for your help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using Windows.Storage;
using SQLite;
namespace illnessTracker
{
public partial class Page1 : PhoneApplicationPage
{
public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ilac.sqlite"));
public Page1()
{
InitializeComponent();
}
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
using (SQLiteConnection dbConn = new SQLiteConnection("Data Source=ilac.sqlite; FailIfMissing=True"))
{
// Create a new task.
hastalik hasta = new hastalik();
hasta.hastalikAdi = txtbxHastalikAdi.Text;
hasta.semptomlar = txtbxSemptomlar.Text;
hasta.ilaclar = tbxIlaclar.Text;
hasta.not = tbxNot.Text;
hasta.doktorTavsiyesi = tbxTavsiye.Text;
hasta.tarihi = DateTime.Now.Date;
/// Insert the new task in the Task table.
dbConn.Insert(hasta);
}
}
[Table("hastalik")]
public class hastalik
{
[Column("hastalikID")]
[PrimaryKey, AutoIncrement]
public int hastalikID { get; set; }
[Column("hastalikAdi")]
public string hastalikAdi { get; set; }
[Column("semptomlar")]
public string semptomlar { get; set; }
[Column("ilaclar")]
public string ilaclar { get; set; }
[Column("doktorTavsiyesi")]
public string doktorTavsiyesi { get; set; }
[Column("not")]
public string not { get; set; }
[Column("tarihi")]
public DateTime tarihi { get; set; }
}
}
}

Cascade Delete for MySQL and ASP.NET MVC4

I have create simple asp.net (MVC4) web page with mysql database. There I have two tables (persons and orders), where table orders have FORIGN Key Persons_ID. I whant to create delete function, so, when I delete person from persons table, it will also delete all orders from order table for this person.
For creating models I have used ADO.NET and it create this two models for each tables:
persons.cs
using System.ComponentModel.DataAnnotations;
namespace MvcMySQLTest1.Models
{
using System;
using System.Collections.Generic;
public partial class person
{
public person()
{
this.orders = new HashSet<order>();
}
public int ID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Adress { get; set; }
public string City { get; set; }
public virtual ICollection<order> orders { get; set; }
}
}
orders.cs
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MvcMySQLTest1.Models
{
using System;
using System.Collections.Generic;
public partial class order
{
public int O_Id { get; set; }
public int OrderNo { get; set; }
public Nullable<int> Persons_Id { get; set; }
public virtual person person { get; set; }
}
}
I have also create MainModel - like I container for both models above:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace MvcMySQLTest1.Models
{
public class MainModel
{
public person Persons { get; set; }
public order Orders { get; set; }
}
}
Now for Cascade deleting I have try this - so when I delete Person, it will also delete all Orders for this Person in order table, but this seems not to work:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace MvcMySQLTest1.Models
{
public class MainModel : DbContext //added
{
public person Persons { get; set; }
public order Orders { get; set; }
//added
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<orders>()
.HasOptional(a => a.persons)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
}
May be you can try something like this
modelBuilder.Entity<order>()
.HasRequired(a => a.person)
.WithMany(t => t.order)
.HasForeignKey(d => d.Persons_Id)
.WillCascadeOnDelete(true);
Or try to read more here MSDN Cascade Delete. May something can help from there

Select what columns from table to be serialized to JSON with WebAPI and Entity Framework?

I am using Entity Framework and WebAPI with my AngularJS project. As of now the whole table in the database gets converted to JSON, but I really only need 3 columns. Are there any easy way to fix this?
UPDATE : Here is the automatically generated controller using Entity Framework. The table contains columns with project information like "ProjectID", "Project name", "Customer name" etc. I only want a couple of them, let's say "ProjectID" and "Project name".
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.Http;
using System.Web.Http.Description;
using RetGet;
namespace RetGet.controllers
{
public class ProjectsController : ApiController
{
private censoredname db = new censoredname();
// GET: api/Projects
public IQueryable<Project> GetProject()
{
return db.Project;
}
// GET: api/Projects/5
[ResponseType(typeof(Project))]
public IHttpActionResult GetProject(int id)
{
Project project = db.Project.Find(id);
if (project == null)
{
return NotFound();
}
return Ok(project);
}
// PUT: api/Projects/5
[ResponseType(typeof(void))]
public IHttpActionResult PutProject(int id, Project project)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != project.ProjectId)
{
return BadRequest();
}
db.Entry(project).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Projects
[ResponseType(typeof(Project))]
public IHttpActionResult PostProject(Project project)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Project.Add(project);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = project.ProjectId }, project);
}
// DELETE: api/Projects/5
[ResponseType(typeof(Project))]
public IHttpActionResult DeleteProject(int id)
{
Project project = db.Project.Find(id);
if (project == null)
{
return NotFound();
}
db.Project.Remove(project);
db.SaveChanges();
return Ok(project);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ProjectExists(int id)
{
return db.Project.Count(e => e.ProjectId == id) > 0;
}
}
}
After a lot of googling it seems that when using EF 6 you have to use JSON.NET [DataContract] and [DataMember]. See example.
[DataContract]
public partial class Project
{
[DataMember]
public int ProjectId { get; set; }
public string PROJECT_NUMBER { get; set; }
public string PROJECT_NAME { get; set; }
[DataMember]
public string LONG_NAME { get; set; }
public decimal CUSTOMER_ID { get; set; }
public string CUSTOMER_NAME { get; set; }
}