I have a Backbone project where I have the following model that I want to pass on to .NET for database updating.
var myList = Backbone.Model.extend({
// Default attributes for the todo item.
defaults: function () {
return {
Name: "Default name"
};
},
url: "/my/myList",
"sync": mySyncFunction,
// Ensure that each todo created has `title`.
initialize: function () {
if (!this.get("Name")) {
this.set({ "Name": this.defaults.Name });
}
}
});
Using the following for overriding the sync
function mySyncFunction(method, model, options) {
if (method == 'GET') {
options.url = model.url;
}
else if (method == "create") {
options.url = model.url+"Post";
}
else {
options.url = model.url;
}
Backbone.emulateJSON = true
return Backbone.sync(method, model, options);
}
When creating a new item it is using the model.url+"Post" I assumed and the model.get("Name") contains the correct data. The correct section is executed and the entry in the database is created but the Name is empty.
Although when the .NET Controller handles the post the Name no longer contains any data.
My controller code looks like this.
public class myController : Controller
{
public ActionResult myList()
{
List<myCore.myList> l = new List<myCore.myList>();
l = myCore.myList.ListAll();
return Json(l, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult myListPost(myCore.myList doc)
{
doc.AccountGuid = Guid.NewGuid();
Boolean created = doc.Create();
return Json(doc);
}
[HttpPut]
public ActionResult myListPut(myCore.myList doc)
{
myCore.myList doc1 = new myCore.myList();
doc1.AccountGuid = Guid.Empty;
doc1.Name = "testPut";
Boolean created = doc1.Create();
return Json(doc1);
}
[HttpDelete]
public ActionResult myListDelete(myCore.myList doc)
{
//DeleteDoc(id);
myCore.myList doc1 = new myCore.myList();
doc1.id = Guid.NewGuid();
doc1.AccountGuid = Guid.Empty;
doc1.Name = "testDelete";
Boolean created = doc1.Create();
return Json(doc1);
}
}
Can anyone tell me what to do to get the model/class data into the controller.
The myList class looks like this.
public class myList
{
Guid _id = Guid.Empty;
String _name = String.Empty;
Guid _accountGuid = Guid.Empty;
public Guid id
{
get { return _id; }
set { _id = value; }
}
public String Name
{
get { return _name; }
set { _name = value; }
}
public Guid AccountGuid
{
get { return _accountGuid; }
set { _accountGuid = value; }
}
}
UPDATE
It now looks like it works after removing Backbone.emulateJSON = true
Although I still cant get my delete part to work. It comes up with a 404 error. Only Post and Get works.
It looks like this in the controller.
[ActionName("myList")]
[HttpDelete]
public ActionResult myListDelete(myCore.myList doc)
{
doc.Name += "-DELETE";
return Json(doc);
}
UPDATE
Figured that one out as well.
ASP.NET Handle PUT/DELETE verbs
Although i can seem to pass any model or paramters along with it on order to delete the correct entry in the database.
Change your defaults to
defaults: {
Name: "Default name"
},
Related
i have 2 actions .. one for User and i can add data to User table but for Order table my code didn't works and got catch error
this is my user code (Action in Controller)
[HttpPost]
public ActionResult Register(User user)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
if (blUser.Add(user))
{
return Json(new JsonData() { Success = true });
}
else
{
return Json(new JsonData() { Success = false });
};
}
else
{
return Json(new JsonData() { Success = false });
}
}
and (UserRepository):
public class UserRepository : IDisposable
{
private HairCut.Models.MVCHairDresserDBEntities db = null;
public UserRepository()
{
db = new HairCut.Models.MVCHairDresserDBEntities();
}
public bool Add(HairCut.Models.User entity, bool autoSave = true)
{
try
{
db.Users.Add(entity);
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
else
return false;
}
catch
{
return false;
}
}
i just change User word to Order but when try to insert data to table i got catch and return false
Order code:
[HttpPost]
public ActionResult Reserve(int select, int user,int hdId)
{
Order order = new Order();
order.HairDresserId =hdId;
order.UserId = user;
order.timeCome = (select).ToString();
order.timeNow = DateTime.Now.ToString("dddh");
order.confirm = true;
OrderRepository blOrder = new OrderRepository();
if (blOrder.Add(order))
{
return Json(new JsonData() { Success = true });
}
else
{
return Json(new JsonData() { Success = false });
}
}
OrderRepository is similar UserRepository. so why cant insert ? where is my wrong ?
every time use breackpoint and debug my codes got catch in code return Convert.ToBoolean(db.SaveChanges());
OrderRepository have 2 foreignkey. when i checked entity quick watch, helper show me 2 extra field ( User and HairDresser with null value ) .. maybe i need set value to these ?
or maybe need create MetaData class to check validation like User values ( but i don't think this is my problem )
Model class
using System;
namespace MySystem.Models
{
public class User
{
private string username;
private string age;
public User()
{
}
public User(string username, string age)
{
this.username = username;
this.age = age;
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Age
{
get { return age; }
set { age = value; }
}
}
}
View
#using System.Linq
#model List<MySystem.Models.User>
#using (Html.BeginForm("AddWithHTMLHelperAndModel",
"List<MySystem.Models.User>", FormMethod.Post))
{
if (!Model.Any())
{
<label>Empty</label> // Model is void, why??
#Model.Add(new User("Username1", "35"))// Returns error that void can't be changed to obj.
}
else
{
<label>Model has content.</label>
}
}
Controller
public ActionResult AddWithHTMLHelperAndModel()
{
List<User> usermodel = new List<User>();
return View(usermodel);
}
[HttpPost]
public ActionResult AddWithHTMLHelperAndModel(List<User> user)
{
var updated_model = user;
return View(updated_model);
}
There appears to be an initialisation problem. No idea why. Before I was able to use the related model just with the reference to it in the beginning of the view (no separate initialisation required).
Also, if I try my User model without the view, just in "main", it works as expected. What am I doing wrong?
The issue was with this:
#Model.Add(new User("Username1", "35"))
Resulting in this error message:
Error message
Removing the leading "#" works. The good syntax is:
Model.Add(new User { Username = "I am in the view!", Age = "15"});
I was mislead in believing that my Model was empty, since it seemed to go into the (!Model.Any()) part.
I hope this can save someone 2 Days of frustration...
In ASP.NET MVC, a field which is declare outside a method, the field is initialize every-time.
There I am giving a demo example.
public class TestController : Controller
{
private List<object> ListItems;
// GET: /Test/Index
public ActionResult Index(int Id)
{
ModelSource _model = new ModelSource(Id);
ListItems = _model.GetItems();//coming info from Model
return View();
}
// GET: /Test/Demo
public ActionResult Demo()
{
int x = ListItems.Count;
//Do Something More
return View(x);
}
}
Is It possible for ListItems will be initialize for once for every client as Id parameter will be different on client's request.
As Patrick Hofman stated you can use Sessions or Cookies Here is an example for both:
Cookies:
string cookievalue ;
if ( Request.Cookies["cookie"] != null )
{
cookievalue = Request.Cookies["cookie"].ToString();
}
else
{
Response.Cookies["cookie"].Value = "cookie value";
}
//For removing cookie use following code
if (Request.Cookies["cookie"] != null)
{
Response.Cookies["cookie"].Expires = DateTime.Now.AddDays(-1);
}
Sessions:
HttpContext.Current.Session.Add("Title", "Data");
string foo = Session["Title"];
I am building a simple MVC CRUD without using a database, but just making methods in a Repository model class.
To make it easier to understand i have 2 model classes. MyNote in which i have some properties and NoteRepository in which i have a list with the properties.
Then I've made a NoteController and i have already made Get and Create methods, but i can't seem to figure out what to write to make an Edit and Delete method? Hope you guys can help.
Here you will see some of the code from my project:
[HttpPost]
public ActionResult Create(MyNote mn)
{
try
{
note.Create(mn);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
this is the create from the Controller.
public static List<MyNote> notes = new List<MyNote>();
public NoteRepository()
{
notes.Add(new MyNote() { ID = 1, Titel = "Morgenmad", OprettelsesDato = DateTime.Now, Note = "Spis morgenmad i dag" });
notes.Add(new MyNote() { ID = 2, Titel = "Frokost", OprettelsesDato = DateTime.Now, Note = "Spis frokost i dag" });
notes.Add(new MyNote() { ID = 3, Titel = "Aftensmad", OprettelsesDato = DateTime.Now, Note = "Spis aftensmad i dag" });
}
public void Create(MyNote mn)
{
notes.Add(mn);
}
here is the repository class with the list and the method for the create method.
and please, ask if i have missed something! Thank you :-)
It looks like you're using a List for your in-memory repository. For delete, you can implement something like this:
public bool Delete (MyNote noteToDelete) {
return notes.Remove(noteToDelete);
}
Edit: However, in this case, the list will check for reference equality. Since you have an ID, which I will assume is unique, you can instead do this:
public bool Delete(MyNote noteToDelete) {
var matchingNote = notes.FirstOrDefault(n => n.ID == noteToDelete.ID);
return notes.Remove(matchingNote);
}
You could also implement IEquatable on your MyNote class to change how your notes are compared with each other, and return a valid match when the IDs are the same.
For the IEquatable example, you would want to change the class definition for MyNote to look like:
public class MyNote : IEquatable<MyNote>
and add in the following code to the MyNote class:
public override bool Equals(object obj) {
if (obj == null) return false;
Part objAsNote = obj as MyNote;
if (objAsNote == null) return false;
else return Equals(objAsNote);
}
public bool Equals(MyNote otherNote) {
if(otherNote == null) return false;
return (this.ID.Equals(otherNote.ID));
}
public override int GetHashCode(){
return this.ID;
}
You can do something like this:
public ActionResult Edit(MyNote noteToEdit)
{
var oldNote = notes.FirstOrDefault(n => n.Id == noteToEdit.Id);
if(oldNote == null)
return View(); //With some error message;
oldNote.Title = noteToEdit.Title;
oldNote.OprettelsesDato = DateTime.Now;
oldNote.Note = noteToEdit.Note;
return RedirectToAction("Index", "Note");
}
public ActionResult Delete(int id)
{
var noteToRemove = notes.FirstOrDefault(x => x.Id == id);
if(noteToRemove == null)
return View(); //With some error message;
notes.Remove(noteToRemove);
return RedirectToAction("Index", "Note");
}
When you are editing your note, i recommend you to use AutoMapper to make your code more easy to maintain.
I've set up this test method on a controller to strip out any complication to it. Based off of all the results I've found from searching this should work. I'm not sure what I'm missing here.
public JsonResult test()
{
return Json(new { id = 1 });
}
This is the error I get.
Cannot implicitly convert type 'System.Web.Http.Results.JsonResult' to 'System.Web.Mvc.JsonResult'
you should return a JsonResult instead of just Json
public JsonResult test()
{
var result = new JsonResult();
result.Data = new
{
id = 1
};
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}
Try the following:
public System.Web.Http.Results.JsonResult test()
{
return Json(new { id = 1 });
}
It seems that Json does not generate a System.Web.Mvc.JsonResult which is expected as you are probably using System.Web.Mvc; but a System.Web.Http.Results.JsonResult.
The more generic one should also work:
public ActionResult test()
{
return Json(new { id = 1 });
}
NOTE:
In my MVC controllers the Json method does return a System.Web.Mvc.JsonResult. Are you inheriting from the default System.Web.Mvc.Controller?
Try
return Json(new { id = 1 }, JsonRequestBehavior.AllowGet);
You need to return the data through a model class rather than an anonymous class. Like:
public System.Web.Http.Results.JsonResult<modelClass> test(){
return Json(new modelClass(){ id=1 });
}
In MVC JsonResult is inherited from ActionResult which is in namespace System.Web.Mvc
thats why you should make the Reference to System.Web.Mvc.JsonResult as::
public System.Web.Mvc.JsonResult test()
{
return Json(new { id = 1 });
}
Put this in your Using:
using System.Web.Http.Results;
Then Your Action:
public JsonResult<YourClass> Get(string Search)
{
var Search = Search
return Json(Search);
}