can't insert data to table in mvc c# - c#

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 )

Related

One Method Accepting Two Different Objects

I have two methods, one to check-in internal users and another to check-in external users. The method is the same except for the object (see code). I was wondering if it's possible to have one method that would accept both objects. I want to pass a parameter that says if it's internal or external, and based on that I want to call the respective object and save it. Not sure if it's possible.
public JsonResult CheckInInternal(int ID)
{
var e = EventInternal.Get(ID, EventInternal.FetchType.ID);
if (e.ID == 0)
{
throw new Exception("Registration ID not found.");
}
if (DateTime.Now.Date > e.EventDetail.StartTime.Date)
{
throw new Exception("Check-in has been closed for this class!");
}
e.CheckedIn = true;
e.Save();
return Json(new { success = true, message = "Success!" });
}
public JsonResult CheckInExternal(int ID)
{
var e = EventExternal.Get(ID, EventExternal.FetchType.ID);
if (e.ID == 0)
{
throw new Exception("Registration ID not found.");
}
if (DateTime.Now.Date > e.EventDetail.StartTime.Date)
{
throw new Exception("Check-in has been closed for this class!");
}
e.CheckedIn = true;
e.Save();
return Json(new { success = true, message = "Success!" });
}
Not saying this is the best way, but you can use Reflection
public enum CallType
{
Internal, External
}
public JsonResult CheckInInternalOrExternal(int ID, CallType type)
{
object e = type == CallType.Internal? EventInternal.Get(ID, EventInternal.FetchType.ID) as object : EventExternal.Get(ID, EventExternal.FetchType.ID) as object;
var idProperty = e.GetType().GetProperty("ID");
var idValue = Convert.ToInt32(IdProperty.GetValue(e));
if (idValue == 0)
{
throw new Exception("Registration ID not found.");
}
if (DateTime.Now.Date > e.EventDetail.StartTime.Date)
{
throw new Exception("Check-in has been closed for this class!");
}
var checkedInProperty = e.GetType().GetProperty("CheckedIn");
checkedInProperty.SetValue(e, true);
var saveMethod = e.GetType().GetMethod("Save");
saveMethod.Invoke(e);
return Json(new { success = true, message = "Success!" });
}
But as some commenters are saying, Interface or Generics is the best solution. Depending on your scenario.

How to make Delete and Edit methods in MVC without DB

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.

How to pass IEnumerable<T> to View

Hello i'm newbie to MVC,
i want to display webgrid in view,I'm trying to display create and display in same page,i'm getting problem at the time of displaying data in webgrid,
This is my code:
Controller:
[HttpPost]
public ActionResult Insert(Torder Model)
{
if(ModelState.IsValid)
{
try
{
ntity.Torders.Add(Model);
ntity.SaveChanges();
ModelState.Clear();
TempData["notice"] = "Successfully registered";
}
catch(Exception ex)
{
TempData["Failure"] = ex;
}
}
else
{
TempData["Failure"] = "Record Not Saved";
}
//var empoyees = Employee.GetList();
IEnumerable<Torder> model1 = GetProducts();
return View(model1);
}
public IEnumerable<Torder> GetProducts()
{
List<Torder> objStudent = new List<Torder>();
///*Create instance of entity model*/
/*Getting data from database for user validation*/
var _objuserdetail = (from data in ntity.Torders
select data);
foreach (var item in _objuserdetail)
{
objStudent.Add(new Torder { Cid = item.Cid, Ccustomername = item.Ccustomername, Citem = item.Citem, Corderamount = (int)item.Corderamount});
}
return objStudent;
}
Just pass your IEnumerable<Torder> like List<Torder> On page you can write foreach loop and create grid
--- Example:
public class Torder
{
public int Id {get;set;}
public string Name {get;set;}
}
[HttpPost]
public ActionResult Insert(Torder Model)
{
if(ModelState.IsValid)
{
try
{
ntity.Torders.Add(Model);
ntity.SaveChanges();
ModelState.Clear();
TempData["notice"] = "Successfully registered";
}
catch(Exception ex)
{
TempData["Failure"] = ex;
}
}
else
{
TempData["Failure"] = "Record Not Saved";
}
//var empoyees = Employee.GetList();
List<Torder> model1 = GetProducts();
return View(model1);
}
public List<Torder> GetProducts()
{
List<Torder> objStudent = new List<Torder>();
// your logic
return objStudent;
}
---------
Page:
-------------
//html code
#model List<Torder>
#foreach(Torder order in Model)
{
// here you can build you grid(table)
order.Name
order.Id
}
P.S In future I recommend write "clean" UI without Razor (Try learn Angular - it's really very good framework) –
It's hard to tell from code in comments, but you might just be missing the #grid.GetHtml()
The block you've shown defines the grid, but now you need to emit the HTML so something shows on the page. Put this after your #{} block right before the closing div tag.

backbone and mvc

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"
},

capturing value of parameter

I really need your help on this guys I am stuck and not sure where to start the fix. So i have this form where the user can select a case and parties. I am supposed save and pass along the values of the selected items. I was able to save the case selections but i am having trouble saving the selected party. Here is my code snippets regarding gathering data and saving them.
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryService:
public void Create(VisitEntry visitEntry,IList<Guid>caseIds, IList<Guid>partyIds )
{
EnsureValid(visitEntry);
_visitEntryRepository.Save(visitEntry);
caseIds = AddCurrentCaseToCases(visitEntry.CaseId, caseIds,partyIds);
foreach (var caseId in caseIds.Distinct())
{
var visit = new Visit {CaseId = caseId, VisitEntryId = visitEntry.VisitEntryId};
_visitService.Create(visit);
}
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
DataContext.SubmitChanges();
}
I am not sure how to get this to save the selected party as it is saving the case information and selected case. Thanks for any feedback!
The save call is a bit earlier so your changes made after your fire SubmitChanges, move the SubmitChanges to the end you should good to go I believe
UPDATE
what I mean is change code like following and see if that helps
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
DataContext.SubmitChanges();
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
}

Categories

Resources