RavenDB in MVC is not saving data to the database - asp.net-mvc

Below are the steps that I've done to use RavenDB in client/server mode (not embedded) for my ASP.Net MVC application. Although I am following exactly the steps but the results are not as expected. Please correct me if there's any mistakes made.
Install RavenDB.Client & RavenDB.Server via Nuget.
Go to Packages folder, start Raven.Server.exe to get the service running
Open http://localhost:8080/ in browser, RavenStudio is up.
Created a database, say named as "testdb"
I have a RestaurantModel.cs.
internal class RestaurantModel{
public string ResName { get; set; }
public string ResAddress { get; set; }
public string ResCity { get; set; }
public string ResState { get; set; }
public int ResPostcode { get; set; }
public string ResPhoneNum { get; set; }
}
In my controller, I've initialized the document store, as well as opening the session.
public ActionResult Index()
{
using (var store = new DocumentStore
{
Url = "http://localhost:8080/",
DefaultDatabase = "testdb"
})
{
store.Initialize();
using (var session = store.OpenSession())
{
session.Store(new RestaurantModel
{
ResName = "TestName",
ResAddress = "Test Address",
ResCity = "TestCity",
ResState = "TestState",
ResPostcode = 82910,
ResPhoneNum = "02-28937481"
});
session.SaveChanges();
}
}
return View();
}
Build the solution. Refresh localhost:8080, data is still not inserted.
I have no idea what am I doing wrong although I'm following exactly all the tutorials I've gone through. So many attempts using different ways but still to no avail.
Thanks in advance for your help!
Tried hitting debug, it opens localhost:33062, but then it shows me server error as shown in below.
# To be more specific #
I have a RestaurantModel.cs
internal class RestaurantModel
{
public string ResName { get; set; }
public string ResAddress { get; set; }
public string ResCity { get; set; }
public string ResState { get; set; }
public int ResPostcode { get; set; }
public string ResPhoneNum { get; set; }
}
I have a AdminController
using FYP2.Models;
using Raven.Client.Document;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FYP2.Controllers
{
public class AdminController : Controller
{
// GET: Admin
public ActionResult Index()
{
using (var store = new DocumentStore
{
Url = "http://localhost:8080/",
DefaultDatabase = "foodfurydb"
})
{
store.Initialize();
using (var session = store.OpenSession())
{
session.Store(new RestaurantModel
{
ResName = "Boxer Republic",
ResAddress = "NO 2A-G, Jalan BK 5A/2C",
ResCity = "Puchong",
ResState = "Selangor",
ResPostcode = 47180,
ResPhoneNum = "03-80748088"
});
session.SaveChanges();
}
}
return View();
}
public ActionResult AdminLogin()
{
return View();
}
public ActionResult AddRestaurant()
{
return View();
}
public ActionResult ManageFoodMenu()
{
return View();
}
public ActionResult ManageOrder()
{
return View();
}
public ActionResult ManageReservation()
{
return View();
}
}
}
I have Admin View, consist of
AddRestaurant, AdminLogin, ManageFoodMenu, ManageOrder, ManageReservation

I really don't know what can cause this problem. Just one question, you just compiled the project or you called your action domain:port/yourcontroller/index?
I've created a mvc project and copied your code:
public class HomeController : Controller
{
internal class RestaurantModel
{
public string ResName { get; set; }
public string ResAddress { get; set; }
public string ResCity { get; set; }
public string ResState { get; set; }
public int ResPostcode { get; set; }
public string ResPhoneNum { get; set; }
}
public ActionResult Index()
{
using (var store = new DocumentStore
{
Url = "http://locaslhost:8080/",
DefaultDatabase = "testdb"
})
{
store.Initialize();
using (var session = store.OpenSession())
{
session.Store(new RestaurantModel
{
ResName = "TestName",
ResAddress = "Test Address",
ResCity = "TestCity",
ResState = "TestState",
ResPostcode = 82910,
ResPhoneNum = "02-28937481"
});
session.SaveChanges();
}
}
return View();
}
}
When I accessed the path http://localhost:50791/ which corresponds to my HomeController/Index, everything went as expected:
Can you give more details about you are trying to do?

Related

how to return json data from mvc controller and view

I am new to mvc so here is my problem I have created a jquery-datatble with a action link named "detalles". When a user clicks on it I what to be able to see the details of the item selected in the jquery-datatble. Once the user has clicked on it. It opens a new tab that has a form with fields and also an other jquery-datatble. Basicly my idea would be to only have one return in the controler that return the view and th json.
Here is my Action result for i "detalles"
public ActionResult Detalles(int? id)
{
proveedorContext proveedorContext = new proveedorContext();
if (id == null)
{
}
proveedorModel proveedor = proveedorContext.GetAllProveedor().Find(obj => obj.proveedor_id == id);
//When i am here my model is not empty
loadProveedorContactoTable(proveedor);
if (proveedor == null)
{
}
return View(proveedor);
}
But unfortunately after words my program calls "loadProveedorContactoTable" again and then my model is completely null
public ActionResult loadProveedorContactoTable(proveedorModel model)
{
try
{
var proveedorsContactoData = model.contactos.OrderBy(a => a.nombre_contacto).ToList();
return Json(new { data = proveedorsContactoData }, JsonRequestBehavior.AllowGet);
}
catch
{
return View();
}
}
Here is my proveedorModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace erp_colombia.Models
{
public class proveedorModel
{
public int proveedor_id { get; set; }
public string nombre { get; set; }
public string direccion { get; set; }
public string codigo_postal { get; set; }
public string cuidad { get; set; }
public string pais { get; set; }
public string pagina_internet { get; set; }
public int compras_cantidad { get; set; }
public int componente_cantidad { get; set; }
public int eliminado { get; set; }
public List<ContactoModel> contactos { get; set; }
}
}
And here is how I read the data for contactos and proveedor()
public List<proveedorModel> GetAllProveedor()
{
List<proveedorModel> list = new List<proveedorModel>();
using (MySqlConnection conn = GetConnection())
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM erp_proveedores",conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new proveedorModel()
{
proveedor_id = int.Parse(reader.GetString(reader.GetOrdinal("proveedor_id"))),
nombre = reader.GetString(reader.GetOrdinal("nombre")),
direccion = reader.GetString(reader.GetOrdinal("direccion")),
codigo_postal = reader.GetString(reader.GetOrdinal("codigo_postal")),
cuidad = reader.GetString(reader.GetOrdinal("cuidad")),
pais = reader.GetString(reader.GetOrdinal("pais")),
pagina_internet = reader.GetString(reader.GetOrdinal("pagina_internet")),
eliminado = int.Parse(reader.GetString(reader.GetOrdinal("eliminado"))),
contactos = new proveedorContactoContext().GetAllProveedorContactos(int.Parse(reader.GetString(reader.GetOrdinal("proveedor_id"))))
});
}
}
return list;
}
}
What can I do to fix this problem thank you for your help. I am thinking about making one return that would return the json and the view how could I so thar

No parameterless constructor defined for this object. (Debug never reaches any controller action?)

I hate these kind of errors.
I have an ASP.NET Core MVC form. When I submit the form I get the dreaded "No parameterless constructor defined for this object." error.
I can't seem to hit anything in the debugger to help me find where I have went wrong.
My controller:
using Brand.Extensions;
using Brand.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Brand.Controllers
{
public class ContentController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Upload()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upload(UploadedContentModel uploadedContentModel, FormCollection formCollection, IFormFileCollection uploadedFiles)
{
ContentExtensions contentExtensions = new ContentExtensions();
FileExtensions fileExtensions = new FileExtensions();
FileModel file = new FileModel();
file = fileExtensions.GetFileModel(uploadedFiles["File"]);
uploadedContentModel.File = fileExtensions.UploadFile(file).ID;
FileModel thumbnail = new FileModel();
thumbnail = fileExtensions.GetFileModel(uploadedFiles["Thumbnail"]);
uploadedContentModel.Thumbnail = fileExtensions.UploadFile(thumbnail).ID;
uploadedContentModel.ID = contentExtensions.UploadContent(uploadedContentModel).ID;
return View();
}
}
}
My model:
public class UploadedContentModel
{
public Guid ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Guid File { get; set; }
public Guid Thumbnail { get; set; }
public string ContentType { get; set; }
public string Solutions { get; set; }
public string Industries { get; set; }
public string AdditionalTags { get; set; }
public DateTime Publish { get; set; }
public DateTime Expire { get; set; }
public string AuthorizedRoles { get; set; }
public string Author { get; set; }
public DateTime Created { get; set; }
}

Httpget Method using asp.net mvc in controller

Fetch data from database some error occur here (AdminPurpose con = i.a ) Message show Cannot implicitly converted type.Please see below for my code snippets:
public JsonResult GetInfor()
{
List<AdminPurpose> all = new List<AdminPurpose>();;
using (db_Hajj_UmrahEntities dc= new db_Hajj_UmrahEntities()) {
var datas = (from a in dc.Duas join b in dc.Purposes on a.PurposeId equals b.Id
select new {
a,
b.PurPose1
});
if(datas != null) {
foreach (var i in datas)
{
AdminPurpose con = i.a ;
con.PurPose1 = i.PurPose1;
all.Add(con);
}
}
}
return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Model class one to many relation here it's using
[MetadataType(typeof(DuaMetaData))]
public partial class AdminPurpose
{
public string PurPose1 { get; set; }
}
public class DuaMetaData
{
public string Dua_Name { get; set; }
public string Arabic_Word { get; set; }
public string Translation_English { get; set; }
public string Source { get; set; }
[Display(Name = "Purpose")]
public int PurposeId { get; set; }
}

How create view for show cookie's info in asp.net mvc using razor?

I'm developing an online store using asp.net mvc 5 and I used cookie for add goods to cart . I want to have a page to show selected items (in cookie) and I don't know how do it, I just wrote an action result for it named Basket . I should use #model List<BasketVM> in my view but when don't know how ?!
could anyone help me please ?
Thanks
GoodController
[HttpGet]
public ActionResult Basket()
{
GoodDetailsRepositories blGoodDetails = new GoodDetailsRepositories();
List<BasketVM> listBasket = new List<BasketVM>();
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = Request.Cookies.Count - 1; i >= 0; i--)
{
if (lst.Where(p => p.Name == Request.Cookies[i].Name).Any() == false)
lst.Add(Request.Cookies[i]);
}
foreach (var item in lst.Where(p => p.Name.StartsWith("NishtmanCart_")))
{
listBasket.Add(new BasketVM {
GoodDetails = blGoodDetails.Find(Convert.ToInt32(item.Name.Substring(13))), Count =Convert.ToInt32(item.Value) });
}
return View(listBasket);
}
BasketVM.cs
public class BasketVM
{
public NP1.Models.GoodDetail GoodDetails { get; set; }
public int Count { get; set; }
}
GoodDetails.cs
public partial class GoodDetail
{
public GoodDetail()
{
this.FactorItems = new HashSet<FactorItem>();
}
public int DetailsGoodID { get; set; }
public int FKSubGoods { get; set; }
public string NishtmanCode { get; set; }
public string DetailsColor { get; set; }
public string DetailsExist { get; set; }
public long DetailsNowPrice { get; set; }
public Nullable<long> DetailsPrePrice { get; set; }
public string DetailsName { get; set; }
public string DetailsLeatherType { get; set; }
public string DetailsWeight { get; set; }
public string DetailsSize { get; set; }
public string DetailsProducer { get; set; }
public string DetailsExtraInfo { get; set; }
public string DetailsURL { get; set; }
public string DetailsKeyWords { get; set; }
public string DetailsTags { get; set; }
public int DetailsLike { get; set; }
public int DetailsDisLike { get; set; }
public string DetailsImage1 { get; set; }
public string DetailsSmallImage1 { get; set; }
public string DetailsImage2 { get; set; }
public string DetailsSmallImage2 { get; set; }
public string DetailsImage3 { get; set; }
public string DetailsSmallImage3 { get; set; }
public string DetailsImage4 { get; set; }
public string DetailsSmallImage4 { get; set; }
public virtual SubGood SubGood { get; set; }
public virtual ICollection<FactorItem> FactorItems { get; set; }
}
Add to cart code
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
catch(Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = "alert('Good didn't add');",
Html = ""
}
);
}
}
with what name you are saving the cookies you can retrieve like this let say userid u want to get rest what you have wriiten will work:
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Userid"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
// retrieve cookie data here
}
how to call in view :
Viewbag.userid = #Request.Cookies["Userid"].value
In order to read a cookie client-side it needs to be created with the HttpOnly flag set to false.
Please go thorugh the below already asked question.
MVC Access stored cookie

The model item passed into the dictionary is of type 'ViewModels.SiteModel',

I'm newbie to MVC architecture.When I'm trying to update, its showing error ,Its totally strange but the data is updating.
The model item passed into the dictionary is of type 'CMS.Domain.Models.Site', but this dictionary requires a model item of type 'CMS.Web.ViewModels.SiteModel'.'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'CMS.Web.ViewModels.SiteModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[CMS.Web.ViewModels.SiteModel]'.
My code looks like:
ViewModels:
namespace CMS.Web.ViewModels
{
public class SiteModel
{
public SiteModel()
{
SiteStatus = new List<SelectListItem>();
}
[Key]
public int ID { get; set; }
[Required(ErrorMessage = "Site Name is required")]
[Display(Name = "Site Name")]
public string Title { get; set; }
[Display(Name = "Require Login")]
public bool RequiresLogin { get; set; }
[Display(Name = "Force HTTPS")]
public bool ForceHTTPS { get; set; }
[Display(Name = "Enable Approval")]
public bool Approval { get; set; }
[AllowHtml]
public IList<SelectListItem> SiteStatus { get; set; }
public bool Deleted { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn
{
get { return _createdOn; }
set { _createdOn = value; }
}
private DateTime _createdOn = DateTime.Now;
public string LastUpdatedBy { get; set; }
public DateTime LastUpdatedOn
{
get { return _lastUpdatedOn; }
set { _lastUpdatedOn = value; }
}
private DateTime _lastUpdatedOn = DateTime.Now;
[Display(Name = "Site State")]
public string SiteState { get; set; }
}
}
Model:
namespace CMS.Domain.Models
{
public partial class Site : Model
{
public string Title { get; set; }
public bool Approval { get; set; }
public bool RequiresLogin { get; set; }
public bool ForceHTTPS { get; set; }
public virtual string SiteStatus { get; set; }
public bool Deleted { get; set; }
}
}
Controller:
public ActionResult Index()
{
var _sites = _siterepository.FindAll();
return View(_sites);
}
public ActionResult Add()
{
var model = new SiteModel();
var _SiteStatus = _siterepository.GetSiteStatus();
foreach (var _sitestatus in _SiteStatus)
{
model.SiteStatus.Add(new SelectListItem()
{
Text = _sitestatus.StatusName,
Value = _sitestatus.StatusName.ToString()
});
}
return View(model);
}
[HttpPost]
public ActionResult Add(SiteModel _sitemodel)
{
var model = _sitemodel.ToEntity();
_siterepository.Add(model);
return View(model);
}
public ActionResult Edit(int id)
{
var model = new SiteModel();
var Site = _siterepository.Find(id);
model = Site.ToModel();
var _SiteStatus = _siterepository.GetSiteStatus();
foreach (var _sitestatus in _SiteStatus)
{
model.SiteStatus.Add(new SelectListItem()
{
Text = _sitestatus.StatusName,
Value = _sitestatus.StatusName.ToString(),
Selected = _sitestatus.StatusName == Site.SiteStatus
});
}
return View(model);
}
[HttpPost]
public ActionResult Edit(SiteModel _sitemodel)
{
var model = _sitemodel.ToEntity();
_siterepository.Update(model);
return View(model);
}
I'm struggling to resolve this , please help.
Check your View's model declaration. It is expecting an enumerable list (IEnumerable<CMS.Web.ViewModels.SiteModel>), but you are passing it a single instance of CMS.Web.ViewModels.SiteModel

Resources