I have data structure for organisation As follows:
public class Organisation
{
public int OrganisationId { get; set; }
[Required]
public string OrganisationCode { get; set; }
[Required]
public string Name { get; set; }
public ICollection<OrganisationSite> Sites { get; set; }
public string TelNo { get; set; }
public int? AddressId { get; set; }
public Address Address { get; set; }
}
An address is stored as its' own entity:
public class Address
{
public int AddressId { get; set; }
[Required]
public string HouseNoName { get; set; }
public string Street { get; set; }
public string Locality { get; set; }
public string TownCity { get; set; }
public string County { get; set; }
[Required]
[RegularExpression("^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$", ErrorMessage="Postcode must be recognisable UK postal code")]
public string Postcode { get; set; }
[Required]
public int AddressTypeId { get; set; }
public AddressType Type { get; set; }
}
Address will be used in many places thoughout an application so sounds like I need a partial view that I can reuse? In my OrganisationController I am going to make a trip to my OrganisationRepository and include the Address entity(entity framework):
public ActionResult Edit(int id = 1)
{
var organisation = _db.Organisation.Include("Address").Single(og => og.OrganisationId == id);
if (organisation == null)
{
return HttpNotFound();
}
return View(organisation);
}
How do I render a partial address view in my Organisation Edit view? I have had a quick look and seen reference to EditorTemplates, is this the approach I need to take, if so do you know of any decent tutorials as the ones I've seen appear fairly deep?
Related
I know this question might be asked so many times, I tried a lot to find the answer and ultimately I am throwing it here if some one can help me.
I am doing a project in ASP.NET Core MVC with a database-first approach. I have a registration form where I need to populate Country and City dropdowns to fill with data coming in through WeCareConext class.
In my controller I am doing this:
[HttpGet]
public IActionResult Register()
{
CompanyEditViewModel model = new CompanyEditViewModel();
var fromDatabaseEF = new SelectList(_context.Country.ToList(), "CountryId", "NameEn");
ViewData["CompanyRegister"] = fromDatabaseEF;
return View(model);
}
My Country model:
public partial class Country
{
public Country()
{
City = new HashSet<City>();
Currency = new HashSet<Currency>();
HolidayType = new HashSet<HolidayType>();
Holidays = new HashSet<Holidays>();
Province = new HashSet<Province>();
StaffInfo = new HashSet<StaffInfo>();
}
public int CountryId { get; set; }
public string NameAr { get; set; }
public string NameEn { get; set; }
public string NameFr { get; set; }
public string IsoCode2 { get; set; }
public string IsoCode3 { get; set; }
public string RegionAr { get; set; }
public string Region { get; set; }
public byte? PostcodeRequired { get; set; }
public bool? IsActive { get; set; }
public byte? IsAvailable { get; set; }
public string MobileMask { get; set; }
public byte? IsDeleted { get; set; }
public int? BaseCharges { get; set; }
public int? MobileNumberLength { get; set; }
public string CountryCode { get; set; }
public byte[] IconImage { get; set; }
public string PickerListAr { get; set; }
public string PickerListEn { get; set; }
public string PickerListFr { get; set; }
public virtual ICollection<City> City { get; set; }
public virtual ICollection<Currency> Currency { get; set; }
public virtual ICollection<HolidayType> HolidayType { get; set; }
public virtual ICollection<Holidays> Holidays { get; set; }
public virtual ICollection<Province> Province { get; set; }
public virtual ICollection<StaffInfo> StaffInfo { get; set; }
}
My CompanyEditViewModel class:
public class CompanyEditViewModel
{
[Display(Name = "Company Number")]
public string CompanyId { get; set; }
[Required]
[Display(Name = "Company Name")]
[StringLength(75)]
public string Name { get; set; }
[Required]
[Display(Name = "Country")]
public string CountryId { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
[Required]
[Display(Name = "City")]
public string SelectedCityCode { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
Unfortunately, this returns an error:
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
I am trying different approaches but not solving my issue. Can anyone suggest some code which can help me and I can also select country and then populate city dropdown according to the CountryID without page reload ? Thanks in advance.
I wonder if someone could help me please. I have a shopping basket which can contain products and each product can contain customers so for instance:
A basket contains the details of the 'purchaser' (FirstName, LastName, etc.) and
Product details (product name, date, etc.) and each product will have
Delegates (people actually attending the event....FirstName, LastName, etc.
What I'm trying to create is a form which shows all of the products with a list of fields underneath allowing the purchaser to enter/amend the names of the people that are attending the event:
What I'm struggling with though is to create the input fields for the attendees. I can use:
foreach(var dele in product.delegates)
{
<p>#dele.FirstName</p>
}
Which does display a list of the names of the attendees as expected but I would expect to be able to use something like:
for(var i=0, i < product.delegates.Count; i++)
{
#Html.TextBoxFor(x => x[i].FirstName)
}
But this displays the name (repeated) of the purchaser and not the attendees.
Could anyone assist please? Like I say I want to display a list of inputs that can amended and posted to an ActionResult to update the DB.
As a note I can see the model is populated with the information that I'm expecting.
public class ShoppingCart
{
public int ShoppingCartId { get; set; }
public DateTime Created { get; set; }
public string TransStatus { get; set; }
public bool Completed { get; set; }
public string ContactNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string CompanyName { get; set; }
public string PostCode { get; set; }
public string Email { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string StoreKey { get; set; }
public DateTime? SentToStore { get; set; }
public virtual ICollection<ShoppingCartProduct> Products { get; set; }
}
public class ShoppingCartProduct
{
public int ShoppingCartProductId { get; set; }
public int ShoppingCartId { get; set; }
public string ProductId { get; set; }
public string CourseId { get; set; }
public string ProductName { get; set; }
public string ProductType { get; set; }
public decimal ItemPrice { get; set; }
public string Location { get; set; }
public DateTime? EventDate { get; set; }
public int Quantity { get; set; }
public decimal TotalPrice => ItemPrice * Quantity;
public virtual ShoppingCart ShoppingCart { get; set; }
public virtual ICollection<ShoppingCartDelegate> delegates { get; set; }
}
public class ShoppingCartDelegate
{
public int ShoppingCartDelegateID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string email { get; set; }
public int ShoppingCartProductId { get; set; }
public virtual ShoppingCartProduct ShoppingCartProduct { get; set; }
}
Sorry buddy, it was me.....the objects were collections and not lists so I was never going to be able to iterate through them with an index. Sorted now. Thanks for you time :)
I am using ValueInjecter to map domain classes to my view models. My domain classes are complex. To borrow an example from this question:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
// VIEW MODEL
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int PersonId { get; set; }
public int AddressId { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
I have looked at FlatLoopInjection, but it expects the view model classes to be prefixed with nested domain model type like so:
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
public int AddressId { get; set; }
public string AddressCity { get; set; }
public string AddressState { get; set; }
public string AddressZip { get; set; }
}
The OP in the linked question altered his view models to match the convention expected by FlatLoopInjection. I don't want to do that.
How can I map my domain model to the original unprefixed view model? I suspect that I need to override FlatLoopInjection to remove the prefix, but I am not sure where to do this. I have looked at the source for FlatLoopInjection but I am unsure if I need to alter the Match method or the SetValue method.
you don't need flattening, add the map first:
Mapper.AddMap<Person, PersonViewModel>(src =>
{
var res = new PersonViewModel();
res.InjectFrom(src); // maps properties with same name and type
res.InjectFrom(src.Address);
return res;
});
and after that you can call:
var vm = Mapper.Map<PersonViewModel>(person);
I'm trying to write a View Model in an ASP.NET MVC5 project to show data from different tables on a form that the user can then edit and save. I'm using the following :-
VS 2017, c#, MySQL Database, Entity Framework 6.1.3, MySQL Connector 6.9.9, Code First from Database (existing database that I can't change)
To complicate matters, there are no links between the tables in the database, so I cannot work out how to create a suitable View Model that will then allow me to save the changes.
Here are the 4 table models :-
public partial class evc_bearer
{
[Key]
[Column(Order = 0]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long evcid { get; set; }
[Key]
[Column(Order = 1]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long bearerid { get; set; }
public int vlan { get; set; }
[Column("ref")]
public string _ref { get; set; }
[Required]
public string port { get; set; }
[Required]
public string endpoint { get; set; }
}
public partial class bearer
{
[Key]
public long id { get; set; }
[Column("ref")]
[Required]
public string _ref { get; set; }
public string name { get; set; }
public long? site { get; set; }
public long? provider { get; set; }
public long? mtu { get; set; }
public float? rental { get; set; }
public int? offsiteprovider { get; set; }
public float? offsiteproviderrental { get; set; }
public bool? aend { get; set; }
public int? equipmentport { get; set; }
public string orderref { get; set; }
public string offsiteref { get; set; }
public string notes { get; set; }
public float? bookingfactor { get; set; }
}
public partial class evc
{
[Key]
public long id { get; set; }
[Required]
public string type { get; set; }
public byte servicetype { get; set; }
public byte cos { get; set; }
public int cir { get; set; }
public int pir { get; set; }
public bool burst { get; set; }
[Column("ref")]
public string _ref { get; set; }
public string orderref { get; set; }
public byte state { get; set; }
public string notes { get; set; }
public float? rental { get; set; }
}
public partial class evc_provider
{
[Key]
public long id { get; set; }
[Required]
public string provider { get; set; }
}
This is the View Model I tried writing :-
public partial class evcBearersVM
{
[Key]
[Column(Order = 0)]
public long evcid { get; set; }
[Key]
[Column(Order = 1)]
public long id { get; set; }
[Column("ref")]
public string b_ref { get; set; }
public string b_name { get; set; }
public string ep_provider { get; set; }
public int eb_vlan { get; set; }
public string eb_port { get; set; }
public string eb_endpoint { get; set; }
}
This is the Linq query I used to populate the View Model :-
IQueryable<evcBearersVM> data = from eb in csdb.evc_bearers
join b in csdb.bearers on eb.bearerid equals b.id
join ep in csdb.evc_providers on b.provider equals ep.id
join e in csdb.evcs on eb.evcid equals e.id
where (eb.evcid == evcid && b.id == id)
select new evcBearersVM
{
evcid = eb.evcid,
id = b.id,
b_ref = b._ref,
b_name = b.name,
ep_provider = ep.provider,
eb_vlan = eb.vlan,
eb_port = eb.port,
eb_endpoint = eb._ref
};
So the query works and joins the tables to get the data I need and I can display this date in various views as needed. What I now need to do is be able to edit a row and save it back to the database. I have an Edit View that is showing the data I need but I'm not sure how to save changes given that it's a View Model and the DB Context isn't aware of it. Grateful for any help.
What you should do is, use the same view model as your HttpPost action method parameter and inside the action method, read the entities you want to udpate using the Id's (you can get this from the view model, assuming your form is submitting those) and update only those properties you need to update.
[HttpPost]
public ActionResult Edit(evcBearersVM model)
{
var b = csdb.bearers.FirstOrDefault(a=>a.id==model.id);
if(b!=null)
{
b.name = model.b_name;
b._ref = model.b_ref;
csdb.SaveChanges();
}
// Update the other entity as well.
return RedirectToAction("Index");
}
i have a problem with my join in my asp.net .. i have two database tables.. named APPLICANT and Profile...they have the same fields.. meaning if the Last name in applicant is null the last name is already in profile table. I already connect my program to the applicant table.. but it have so many null fields that have to fetch from the profile data table.... sorry i'm new in asp.net ...
Here's my code in controller:
public View Result Index()
{
var applicants = (from a in db.APPLICANTs
select a).ToList();
return View(applicants);
}
heres my context:
public partial class APPLICANT
{
public int APPLICANT_ID { get; set; }
public Nullable<int> Profile_id { get; set; }
public string APPLICANT_LastName { get; set; }
public string APPLICANT_FirstName { get; set; }
public string APPLICANT_MiddleName { get; set; }
public string APPLICANT_Address { get; set; }
public string APPLICANT_City { get; set; }
public string APPLICANT_ZipCode { get; set; }
public string APPLICANT_Phone { get; set; }
public string APPLICANT_Email { get; set; }
}
public partial class Profile
{
public int PROFILE_ID { get; set; }
public string Applicant_LASTNAME { get; set; }
public string Applicant_FIRSTNAME { get; set; }
public string Applicant_MIDDLENAME { get; set; }
public string Applicant_EMAIL { get; set; }
public string Applicant_PHONE { get; set; }
public string Applicant_ADDRESS { get; set; }
public string Applicant_ZIPCODE { get; set; }
public string Applicant_CITY { get; set; }
}
thanks for those who can help my problem..