2 Models of same Properties, MVC3 - asp.net-mvc-3

Good Day guys!
I've just started using MVC3, I've 2 models in my application i.e. "Page" and "PageHistory" both has same properties. except that "PageHistory" has one extra property called "PageId" which references the "Page" model.
My question is am doing it in correct way? or should I use inheritance for this.
If inheritance is a option, How can I handle this, any examples will help me a lot.
My Model looks like as follows:
public class Page
{
private readonly IndianTime _g = new IndianTime();
public Page()
{
CreatedOn = _g.DateTime;
Properties = "Published";
Tags = "Page";
RelativeUrl = string.Empty;
}
public string Path
{
get { return (ParentPage != null) ? ParentPage.Heading + " >> " + Heading : Heading; }
}
[Key]
public int Id { get; set; }
[StringLength(200), Required, DataType(DataType.Text)]
public string Title { get; set; }
[StringLength(200), Required, DataType(DataType.Text)]
public string Heading { get; set; }
[MaxLength, Required, DataType(DataType.Html)]
public string Content { get; set; }
[Display(Name = "Reference Code"), ScaffoldColumn(false)]
public string ReferenceCode { get; set; }
[Required]
[Remote("CheckDuplicate", "Page", ErrorMessage = "Url has already taken", AdditionalFields = "initialUrl")]
public string Url { get; set; }
[Display(Name = "Created On"), ScaffoldColumn(false)]
public DateTime CreatedOn { get; set; }
//Parent Page Object (Self Reference: ParentId = > Id)
[Display(Name = "Parent Page")]
public int? ParentId { get; set; }
[DisplayFormat(NullDisplayText = "Root")]
public virtual Page ParentPage { get; set; }
public virtual ICollection<Page> ChildPages { get; set; }
}

I don't think inheritance will be the right way, the current structure looks ok to me.
See if you choose to make the Page as parent, and Pagehistory as being inherited from Page which actually it is not its just the pagehistory quite simply put.
Your idea of inheritance should always come from real world implementations, for ex. there could be diff. kinds of pages all inheriting from a Super Page type, while Page history is just a property to the page rather a complex property with properties inside it.

Related

AJAX Posting Slickgrid data to MVC

I have a slickgrid and am attempting to save its data back to the server.
When I breakpoint on the server, I can see the data in the Request.Form object, but I can't make it work with my object.
My data looks like...
[
{"id":"0","LineNumber":"","Detail":"MOT cost","Code":" ","Qty":"1","Est":" ","CustomerDamage":false,"Cost":"44.00","Value":"44.00","VAT":true,"SelfBillingLine":"False","DefectStatus":" "},
{"id":"62","LineNumber":"","Detail":"CRACKS IN Chassis","Code":"TLMA02","Qty":"1","Est":"","CustomerDamage":false,"Cost":"35.00","Value":"35.00","VAT":true,"SelfBillingLine":"False","DefectStatus":"Large repair"},
{"id":"63","LineNumber":"","Detail":"TEAR IN N/S CURTAIN","Code":"TLMA02","Qty":"1","Est":"","CustomerDamage":true,"Cost":"10.00","Value":"10.00","VAT":true,"SelfBillingLine":"False","DefectStatus":"Customer"}
]
I am posting with a button onclick...
$("#SBSave").click(function() {
debugger;
var details = JSON.stringify(defectrows);
save('SBDetail/SaveSBItem', details);
});
I have tried a number of things to receive the data, none of them work.
My controller...
[HttpPost]
public void SaveSBItem(SelfBillDetailList details, string Approve = "")
{
// Actions here.
}
My model...
Trying a number of things, neither work...
public class SelfBillDetailList
{
public IEnumerable<SelfBillingIncomingDetail> IncomingDetails { get; set; }
}
public class SelfBillingIncomingDetail
{
public int id { get; set; }
public string Code { get; set; }
public string LineNumber { get; set; }
public string Detail { get; set; }
public string Action { get; set; }
public string Qty { get; set; }
public string Est { get; set; }
public bool VAT { get; set; }
public bool CustomerDamage { get; set; }
public string Cost { get; set; }
public string Value { get; set; }
public DateTime Received { get; set; }
public string DefectStatus { get; set; }
public bool SelfBillingLine { get; set; }
}
So, I have tried an individual SelfBillingIncomingDetail and also a the SelfBillDetailList.
Neither work.
I have even sent an individual row, again, neither work.
I want to send it as a group, so it will be an array of SelfBillingIncomingDetail but nothing works.
Thank you for your help.
I have done it again... eventually found an answer after looking for ages.
Darin Dimitrov's answer in
Post an Array of Objects via JSON to ASP.Net MVC3
let me to the answer.
It seems that when sending the data, I need to give the array of data the same name as the property name in SelfBillDetailList, so...
var details = JSON.stringify({IncomingDetails : defectrows});
fixes it.

update modelobject in a controller

I am trying to update user in my model object
public ActionResult AddJob(JobQueue job,HttpPostedFileBase file)
{
job.User = "itdev";
TryUpdateModel(job)
if (ModelState.IsValid)//Always returns false
{
}
}
MODEL
public class JobQueue {
[Required]
[Display(Name="JobId")]
public string JobId { get; set; }
[Required] [Display(Name = "FileName")]
public string FileName { get; set; }
[Required]
[Display(Name = "Job Run Date")]
public DateTime JobRunDate { get; set; }
[Required]
[Display(Name = "Email")]
public string Mail { get; set; }
[Required]
[Display(Name = "User")]
public string User { get; set; }
I tried using TryUpdateModel(job) and UpdateModel(job) after assigning the values.Both of these does not seem to update the model because ModelState.IsValid return false.Can someone point me in the right directions?I am using MVC3
Thanks,
Sab
I may be wrong here, but I think job.User = "itdev"; should be sufficent to update the model without using the TryUpdateModel(job) thats how we do it in our site anyway. I have never need to use any method to actually update the model itself. Just assigned values manually.
It depends on how your model is setup I guess.
You should probably post the code for your model just in case my answer isnt helpful.

The 'SubCatNewsID' property on 'SubCatNews' could not be set to a 'Boolean' value. You must set this property to a non-null value of type 'Int32

I'm getting this error some time, without any action I do
This appears at random
I use this frameworks:
Entity in CodeFirst type,Mvc3
Sometimes I get this erros in diffrent data types or for other models:
The 'CatID' property on 'Cat' could not be set to a 'Boolean' value. You must set this property to a non-null value of type 'Int32
or
The 'CatID' property on 'Cat' could not be set to a 'String' value. You must set this property to a non-null value of type 'Int32
my site subject is news publishing and my client operators work with site and insert/edit data During all off day
Edit:
i see that this erros is not for a page,when i have this error,no page in my site not load and all of the pages have this message
my model:
public class SubCatNews
{
[Key]
public int SubCatNewsID { get; set; }
// [EdmScalarPropertyAttribute(IsNullable = true)]
// public int? SubCatID { get; set; }
[Required(ErrorMessage = "some error")]
public string Title { get; set; }
[Required(ErrorMessage = "some error")]
[AllowHtml]
[DataType(DataType.Html)]
public string Summary { get; set; }
[Required(ErrorMessage = "some error")]
[AllowHtml]
[DataType(DataType.Html)]
public string Details { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public bool? ImpStatus { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? Created { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public bool? Visible { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public string pic { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? UsersID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? StatusID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? NewsTypeID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? ZonesID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? lanID { get; set; }
//public int RatingSubCatNewsID { get; set; }
public virtual Users Users { get; set; }
// public virtual SubCat SubCat { get; set; }
public virtual NewsStatus Status { get; set; }
public virtual NewsType NewsType { get; set; }
public virtual ICollection<SubCatNewsComment> SubCatNewsComments { get; set; }
public virtual ICollection<NewsInSubCat> NewsInSubCatss { get; set; }
public virtual ICollection<SubNewsInTag> SubNewsInTags { get; set; }
//public virtual RatingSubCatNews RatingSubCatNews { get; set; }
}
But i`m wondering that when i make any change in web.config,site is up!
i thing this is for caching data and values in Entity
my Context Creator:
public abstract class BaseController<TEntityType, TIdType> : ContextGridController<HNewsPortalContext, TEntityType, TIdType>
where TEntityType : class
{
protected override HNewsPortalContext CreateContext()
{
return new HNewsPortalContext();
}
}
before this time,my Context Creator,return Context like this:
HNewsPortalContext.Singleton;
i guess this was for static context and entity caching make this error,but newing context,do not fix my error
now when my site have this error,i make a little change(switch Custom Error Mode value between Off or RemoteOnly) in web.config and save it,then site is up
please help me
tanx
my full error message:
full message image
full message image
Attach debugger, break on exception and check the stack trace to see what code is setting your properties.
i checked and see that was because overflowing my application pool
my site was on a shared server and session expire time was very long
finish

asp.net mvc3 UpdateModel exclude properties is not working

I have a class, which has 8 props / 8 columns in DB. But on a Edit page, i dont want to show the AddedDate or UserID field, since i dont want user to change it.
public class Voucher
{
public int ID { get; set; }
public string Title { get; set; }
public string SiteName { get; set; }
public string DealURL { get; set; }
public DateTime AddedDate { get; set; }
public DateTime? ExpirationDate { get; set; }
public string VoucherFileURL { get; set; }
public Guid UserID { get; set; }
}
Here is what I have for Edit controller:
// POST: /Voucher/Edit/5
[HttpPost]
public ActionResult Edit(Voucher voucher)
{
if (ModelState.IsValid)
{
string[] excludeProperties = { "AddedDate", "UserID" };
UpdateModel(ModelState, "", null, excludeProperties);
db.Entry(voucher).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(voucher);
}
On Edit page, once i click on submit, i got the following error: System.Data.SqlServerCe.SqlCeException: An overflow occurred while converting to datetime.
Seems like the AddedDate didn't get excluded from the view model and triggered the error.
Would you please let me know how to fix it? Thanks!
public ActionResult Edit([Bind(Exclude = "AddedDate")]Voucher voucher)
no luck either
You are still passing in Voucher which could contain that field in it. I'm not sure what you are trying to accomplish with the UpdateModel here if you are already passing in a Voucher object?
Pass in Voucher, set it to modified and save it. If you want to use whats in the database then you'll have to
Load the object from the database
UpdateModel and exclude the properties
Save your entity.
You could simply use a View Model and post that.
public class Voucher
{
public int ID { get; set; }
public string Title { get; set; }
public string SiteName { get; set; }
public string DealURL { get; set; }
public DateTime? ExpirationDate { get; set; }
public string VoucherFileURL { get; set; }
public Guid UserID { get; set; }
}
and then load up your object from the db":
var voucher = db.Vouchers.Where(o=>o.ID==voucherViewModel.Id);
//manually copy the fields here then save it
//copy
db.SaveChanges();

Asp.Net MVC3 - How create Dynamic DropDownList

I found many articles on this but still I don´t know how exactly to do this. I am trying to create my own blog engine, I have View for create article (I am using EF and Code first) and now I must fill number of category in which article should be add but I want to change it to dropdownlist with names of categories. My model looks this:
public class Article
{
public int ArticleID { get; set; }
[Required]
public string Title { get; set; }
[Required]
public int CategoryID { get; set; }
public DateTime Date { get; set; }
[Required()]
[DataType(DataType.MultilineText)]
[AllowHtml]
public string Text { get; set; }
public virtual Category Category { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
I know I must use Enum (or I think) but I am not exactly sure how. I don´t know which tutorial from that I found is best for me.
Edit:
Thanks for your answers but I found something else. I am trying this:
This is my model:
public class Article
{
[Key]
public int ArticleID { get; set; }
[Display(Name = "Title")]
[StringLength(30, MinimumLength = 5)]
[Required]
public string Title { get; set; }
public DateTime Date { get; set; }
public int CategoryID { get; set; }
[Required()]
[DataType(DataType.MultilineText)]
[AllowHtml]
public string Text { get; set; }
public Category Category { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int CategoryId { get; set; }
[Required]
public string CategoryName { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
This is my controller to create article:
public ActionResult Vytvorit()
{
IEnumerable<Category> categories = GetCaregories();
var view = View(new Article() { Categories = categories });
view.TempData.Add("Action", "Create");
return view;
}
private static IEnumerable<Category> GetCaregories()
{
IEnumerable<Category> categories;
using (BlogDBContext context = new BlogDBContext())
{
categories = (from one in context.Categories
orderby one.CategoryName
select one).ToList();
}
return categories;
}
private Category GetCategory(int categoryID)
{
return db.Categories.Find(categoryID);
}
//
// POST: /Clanky/Vytvorit
[HttpPost]
public ActionResult Vytvorit(Article newArticle)
{
try
{
if (newArticle.CategoryID > 0)
{
newArticle.Category = GetCategory(newArticle.CategoryID);
}
if (TryValidateModel(newArticle))
{
db.Articles.Add(newArticle);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
newArticle.Categories = GetCaregories();
var view = View(newArticle);
view.TempData.Add("Action", "Create");
return view;
}
}
catch
{
return View();
}
}
And this is part of my view:
#Html.DropDownListFor(model => model.CategoryID, new SelectList(Model.Categories,"CategoryID","CategoryName"))
#Html.ValidationMessageFor(model => model.CategoryID)
I have problem with NullReferenceExeption but I don´t know why. Can I do it this way? It looks very easy for me.
Your model seems quite strange. It contains properties such as CategoryID and Category which seem redundant. It also contains a SelectListItem collection property called Categories. So, is this a model or a view model? It looks quite messed up. Let's assume it's a model. In this case it would more likely look something like this:
public class Article
{
public int ArticleID { get; set; }
[Required]
public string Title { get; set; }
public DateTime Date { get; set; }
[Required()]
[DataType(DataType.MultilineText)]
[AllowHtml]
public string Text { get; set; }
public virtual Category Category { get; set; }
public IEnumerable<Category> Categories { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
Now that the model is clear we could define a view model which will be passed to the view. A view model is a class which is specifically designed for the view. So depending on what you intend to put in this view you define it in this view model. So far you have talked only about a drop down, so let's do it:
public class ArticleViewModel
{
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
and then we have a controller:
public class ArticlesController: Controller
{
private readonly IArticlesRepository _repository;
public ArticlesController(IArticlesRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
Article article = _repository.GetArticle();
ArticleViewModel viewModel = Mapper.Map<Article, ArticleViewModel>(article);
return View(viewModel);
}
}
So the controller uses a repository to fetch the model, maps it to a view model (in this example I use AutoMapper) and passes the view model to the view which will take care of showing it:
#model AppName.Models.ArticleViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.SelectedCategoryId,
new SelectList(Model.Categories, "Value", "Text"),
"-- Select category --"
)
<input type="submit" value="OK" />
}
I have gone through this as well and I have to agree that at first it seems odd (In my explanation I'm assuming you want to select one category only, but the process is very similar for a multi select).
Basically you need to perform 3 steps:
1:
You need two properties on your viewmodel
One will hold the selected category id (required for postback) and the other will a SelectList with all possible categories:
public class Article
{
public int ArticleID { get; set; }
public int CategoryID { get; set; }
public SelectList Categories { get; set; }
}
2:
Also before passing the viewmodel on to the view you need to initialize the SelectList (Best practivce is to prepare as much as possible before passing a model into the view):
new SelectList(allCategories, "CategoryID", "Name", selectedCategoryID)
3:
In the view you need to add a ListBox for the CategoryID property, but using the Categories property too fill the ListBox with values:
#Html.ListBoxFor(model => model.CategoryID , Model.Categories)
Thats it! In the post back action of the controller you will have the CategoryID set. You can do whatever you need to from there to persist things in your db.

Resources