I have a Entity class
public class SiteMenu
{
public int MenuID { get; set; }
public string MenuName { get; set; }
public string NavURL { get; set; }
public int ParentMenuID { get; set; }
}
I want to create a collection of SiteMenu by the following code:
List<SiteMenu> all = new List<SiteMenu>();
To create and add an SiteMenu object to the List is this the correct format/syntax
all.Add(new SiteMenu(MenuID=1, MenuName="Test1", NavURL="http://test", ParentMenuID=0));
I like to use one line and keep adding to the list.
THanks.
You can use the collection initializer syntax to create the list and add the initial elements in one line:
var all = new List<SiteMenu> { new SiteMenu { MenuID = 1, MenuName = "Test1", NavURL = "http://test", ParentMenuID = 0} };
List<SiteMenu> list = new List<SiteMenu> {
all.Add(new SiteMenu(MenuID=1, MenuName="Test1", NavURL="http://test", ParentMenuID=0));
};
You should use a constructor.
public class SiteMenu
{
public int MenuID { get; set; }
public string MenuName { get; set; }
public string NavURL { get; set; }
public int ParentMenuID { get; set; }
public SiteMenu(int menuID, string menuName, string navURL, int parentMenuID) {
MenuID = menuID;
MenuName = menuName;
NavURL = navURL;
ParentMenuID = parentMenuID;
}
}
Then you can do:
List<SiteMenu> all = new List<SiteMenu>();
all.Add(new SiteMenu(1, "Test1", "http://test", 0));
Related
I have a view that has add/edit, edit is working fine but for add I would like to set default values for type. Is there a way to do this in the view the cshtml file?
add view
#Html.Partial("RegimenReferences", new (ReferencesModel {Type = "defaultType}") )
edit view
#Html.Partial("RegimenReferences", (ReferencesModel)Model)
Model
public class ReferencesModel
{
public ReferencesModel()
{
}
public ReferencesModel(Reference reference)
{
this.Id = reference.Id;
this.Link = reference.Link;
this.Text = reference.Text;
this.Type = reference.Type;
this.Regimens = reference.Regimens;
this.GuidelineId = reference.GuidelineId;
this.SortOrder = reference.SortOrder;
}
public long Id { get; set; }
public string Link { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public int Regimens { get; set; }
public Guid? GuidelineId { get; set; }
public int SortOrder { get; set; }
}
}
Are you wanting to set those types specifically in cshtml?
Could you create a new constructor for your model that takes in any fields you want to set with a default?
public class ReferencesModel
{
public ReferencesModel(string type = null)
{
Type = type;
}
public ReferencesModel(Reference reference)
{
this.Id = reference.Id;
this.Link = reference.Link;
this.Text = reference.Text;
this.Type = reference.Type;
this.Regimens = reference.Regimens;
this.GuidelineId = reference.GuidelineId;
this.SortOrder = reference.SortOrder;
}
public long Id { get; set; }
public string Link { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public int Regimens { get; set; }
public Guid? GuidelineId { get; set; }
public int SortOrder { get; set; }
}
or just set a default value in the constructor/in variable declaration
public ReferencesModel()
{
Type = "default type";
}
public string Type = "default type";
I am testing my controller code using IOC Unity. The issue is with the initialisation of the model that I am passing to constructor of my controller.
Here is my code in the test project
[TestMethod]
public void TestHomeControllerIndexMethod()
{
HomeController controller = new HomeController(new stubPeopleService());
ViewResult result = controller.Index() as ViewResult;
Assert.AreEqual(0, result);
}
Below is the code of the stubPeopleService that I have created which I pass to my controller constructor above
public class stubPeopleService : IPeople
{
public int Age
{
get;
set;
}
public string BirthPlace
{
get;
set;
}
public DateTime DateOfBirth
{
get;
set;
}
public int GetAge(DateTime reference, DateTime birthday)
{
int age = reference.Year - birthday.Year;
if (reference < birthday.AddYears(age)) age--;
return age + 1;
}
public int Height
{
get;
set;
}
public List<People> listPeople { get { return GetPeople(); } }
public string Name
{
get;
set;
}
public int Weight
{
get;
set;
}
private List<People> GetPeople()
{
List<People> list = new List<People>();
list.Add(new People
{
Name = "Ranjit Menon",
DateOfBirth = DateTime.Today,
BirthPlace = "London",
Age = 25,
Height = 175,
Weight = 85
});
return list.OrderBy(x => x.Name).ToList();
}
}
When I debug my test , I notice that the all the properties do not contain any value. The only property that contains value is listPeople property. The listpeople property does initialise the other properties but throws an object cannot be created error.Let me know if I am doing the test correctly. I need to do a test initialising the model with some values.
Code from my home controller
private IPeople peopleService;
public HomeController(IPeople people)
{
this.peopleService = people;
}
public ActionResult Index()
{
return View(peopleService);
}
Please find the IPeople interface below
public interface IPeople
{
int Age { get; set; }
string BirthPlace { get; set; }
DateTime DateOfBirth { get; set; }
int GetAge(DateTime reference, DateTime birthday);
int Height { get; set; }
List<People> listPeople { get; }
string Name { get; set; }
int Weight { get; set; }
}
Select doesn't work for me with DropDownListFor. Can anyone help me?
I have musiccategories and artists that belong to one musiccategory. On my page I want to show artist details, and I want the dropdownlist to load all musiccategories with the specified artists music category selected. But I can't make one specified option in the drop down list selected, the first option is always selected at first.
My controller:
public ActionResult Index()
{
ClassLibrary.Artist a = GetArtist();
System.Collections.Generic.List<System.Web.Mvc.SelectListItem> items = getGenres();
string genre = a.MusicCategory;
foreach (SelectListItem sli in items)
{
if (sli.Text == genre)
{
sli.Selected = true;
}
}
ViewBag.MusicCategory = items;
return View(a);
}
My first model:
public class MusicCategory
{
public int MusicCategoryID { get; set; }
public string MusicCategoryName { get; set; }
}
My secound model:
public class Artist
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public string MusicCategory { get; set; }
public int MusicCategoryID { get; set; }
public int Contact { get; set; }
public string InformationToCrew { get; set; }
public string Agreement { get; set; }
public string WantedStage { get; set; }
public string AgreementAccepted { get; set; }
public string PublishingStatus { get; set; }
public string ApplicationStatus { get; set; }
public int? ActiveFestival { get; set; }
public string ImageURL { get; set; }
public string URL { get; set; }
public string FacebookEvent { get; set; }
public int Score { get; set; }
public List<GroupMember> GroupMembers { get; set; }
}
My view:
#Html.DropDownListFor(model => model.MusicCategory, (System.Collections.Generic.List<System.Web.Mvc.SelectListItem>)ViewBag.MusicCategory)
DropDownListFor, selected = true doesn't work
Yup.
But I can't make one specified option in the drop down list selected, the first option is always selected at first.
When you use
// I don't recommend using the variable `model` for the lambda
Html.DropDownListFor(m => m.<MyId>, <IEnumerable<SelectListItem>> ...
MVC Ignores .selected and instead verifies the m.<MyId> value against the values in <IEnumerable<SelectListItem>>.
public class DropDownModel
{
public int ID3 { get; set; }
public int ID4 { get; set; }
public int ID5 { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
public ActionResult Index()
{
var model = new DropDownModel
{
ID3 = 3, // Third
ID4 = 4, // Second
ID5 = 5, // There is no "5" so defaults to "First"
Items = new List<SelectListItem>
{
new SelectListItem { Text = "First (Default)", Value = "1" },
new SelectListItem { Text = "Second (Selected)", Value = "2", Selected = true },
new SelectListItem { Text = "Third", Value = "3" },
new SelectListItem { Text = "Forth", Value = "4" },
}
};
return View(model);
}
<div>#Html.DropDownListFor(m => m.ID3, Model.Items)</div>
<div>#Html.DropDownListFor(m => m.ID4, Model.Items)</div>
<div>#Html.DropDownListFor(m => m.ID5, Model.Items)</div>
Result:
dotnetfiddle.net Example
Maybe it has something to do with the way you populate your selec list items or your model.
You can take a look at this post :
How can I reuse a DropDownList in several views with .NET MVC
At first I should say i am compeletely newbie in MVC.
I have 3 Objects
public partial class Magazine
{
public Magazine()
{
this.NumberTitles = new HashSet<NumberTitle>();
}
public int Id { get; set; }
public int MagYear { get; set; }
public int MagNo { get; set; }
public int MagSeason { get; set; }
public string MagYear2 { get; set; }
public virtual ICollection<NumberTitle> NumberTitles { get; set; }
}
public partial class NumberTitle
{
public NumberTitle()
{
this.Articles = new HashSet<Article>();
}
public int Id { get; set; }
public int MagazineId { get; set; }
public int TitleId { get; set; }
public int position { get; set; }
public virtual ICollection<Article> Articles { get; set; }
public virtual Magazine Magazine { get; set; }
public virtual Title Title { get; set; }
}
public partial class Title
{
public Title()
{
this.ChildrenTitle = new HashSet<Title>();
this.NumberTitles = new HashSet<NumberTitle>();
}
public int Id { get; set; }
public string TitleText { get; set; }
public Nullable<int> ParentId { get; set; }
public virtual ICollection<Title> ChildrenTitle { get; set; }
public virtual Title ParentTitle { get; set; }
public virtual ICollection<NumberTitle> NumberTitles { get; set; }
}
In a View I want to have TextBox to show Magazine Number and 2 List boxes. one shows all the Available Titles and the Other just selected Titles for that Magazine Number.So I have made View Model
public class NumberTitleViewModel
{
public Magazine Magazine { get; set; }
public List<NumberTitle> NumberTitles { get; set; }
}
this is in controller. how can i get the list of titles for specified MagazineId
public ActionResult EditTitle(int id)
{
Func<IQueryable<Magazine>, IOrderedQueryable<Magazine>> orderByFunc = null;
Expression<Func<Magazine, bool>> filterExpr = null;
if (id>0)
{
filterExpr = p => p.Id.Equals(id);
}
Magazine magazine = unitOfWork.MagazineRepository.Get(filter: filterExpr, orderBy: orderByFunc, includeProperties: "").SingleOrDefault();
NumberTitleViewModel numberTitleViewMode = new NumberTitleViewModel();
numberTitleViewMode.Magazine = magazine;
Expression<Func<NumberTitle, bool>> filterExpr2 = null;
if (id > 0)
{
filterExpr2 = p => p.MagazineId.Equals(id);
}
var numberTitles = unitOfWork.NumberTitleRepository.Get(filterExpr2, null, includeProperties: "Title").ToList();
var titles = unitOfWork.TitleRepository.Get(null, null, "");
numberTitleViewMode.NumberTitles = numberTitles; ///this part doesn't show the Titles. how should access the TitleName not Id
ViewBag.titles = new SelectList(titles, "Id", "TitleText");
return View("../Panel/Magazine/EditTitle", "_BasicLayout", numberTitleViewMode);
}
Not sure what you have in your view but you should have something like:
#using NameSpace.Models
#model NameSpace.Models.NumberTitleViewModel
Then you can do something like this in your view:
foreach (NumberTitles item in #Model)
{
<label>#item.Title.TitleText</label>
}
Not exact but should get you close to what you need
Most of the tutorials for MVC with Entity Framework are centered around Code-First, where you write classes for generating the model. This gives the advantage of control and Migrations, but I think it lack overview. I would therefore prefer to create the model using the graphical designer, but I cannot see how or if data migrations work in this context. It seems, that when I change the model (with data in the database), all the data is deleted in all tables.
Is there a way around this?
How can I do validation when using Model-First? Partial classes?
you may use the global validation beside mvc validation
example :
public class ValidationCriteria
{
public ValidType Type { get; set; }
public ValidRange Range { get; set; }
public ValidFormat Format { get; set; }
public ValidIsNull IsNull { get; set; }
public ValidCompare Compare { get; set; }
public ValidDB DB { get; set; }
public string Trigger { get; set; }
public Dictionary<string, ValidationCriteria> Before { get; set; }
public string After { get; set; }
public class ValidDB
{
public string functionName { get; set; }
public object[] param { get; set; }
public object functionClass { get; set; }
public string msg { get; set; }
public bool check = false;
}
public class ValidCompare
{
public string first { get; set; }
public string second { get; set; }
public string compareOperator { get; set; }
public string compareValue { get; set; }
public string msg { get; set; }
public bool check = false;
}
public ValidationCriteria()
{
this.Range = new ValidRange();
this.Format = new ValidFormat();
this.IsNull = new ValidIsNull();
this.Type = new ValidType();
this.Compare = new ValidCompare();
this.DB = new ValidDB();
this.Trigger = "blur";
this.Before = new Dictionary<string, ValidationCriteria>();
this.After = "";
}
public class ValidType
{
// checking element is integer.
public bool isInt { get; set; }
// checking element is decimal.
public bool isDecimal { get; set; }
public string msg { get; set; }
public bool check = false;
}
public class ValidRange
{
public long min { get; set; }
public long max { get; set; }
public string msg { get; set; }
public bool check = false;
}
public class ValidFormat
{
public bool isEmail { get; set; }
public string regex { get; set; }
public string msg { get; set; }
public bool check = false;
}
public class ValidIsNull
{
public string nullDefaultVal { get; set; }
public string msg { get; set; }
public bool check = false;
}
}
Meanwhile you may use validation part in your controller
Example :
private bool validateMaintainanceManagement(MaintainanceCRUD.Maintainance model, bool edit = false, bool ServerValidation = true)
{
bool ValidModel = false;
Dictionary<string, ValidationCriteria> validCriteria = new Dictionary<string, ValidationCriteria>();
#region maintainTitle Criteria
ValidationCriteria maintainTitle = new ValidationCriteria();
maintainTitle.IsNull.msg = Resources.Home.ErrmaintainTitle;
maintainTitle.IsNull.check = true;
maintainTitle.IsNull.nullDefaultVal = "-1";
//maintainTitle.Trigger = "change"; // this may trigger if you are using dropdown
validCriteria.Add("maintainTitle", maintainTitle);
#endregion