ViewModel Mvc Display details - asp.net-mvc

So i have 3 models and need to display information in a view that is on the 3 models, so i created a viewModel that contains the info that i need for the view
model 1:
public class Despesa
{
public int TipoDespesaId { get; set; }
public int DespesaId { get; set; }
[Display(Name = "Descrição da Despesa")]
[Required]
public string DespesaDescricao { get; set; }
[Display(Name = "Valor")]
[Required]
public decimal DespesaValor { get; set; }
public int TipoPagamentoId { get; set; }
[Display(Name = "Data")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
[Required]
public DateTime Data { get; set; }
public TipoDespesa TipoDespesa { get; set; }
public TipoPagamento TipoPagamento { get; set; }
[Display(Name = "Comentário")]
public string Comentario { get; set; }
}
model2:
public class TipoDespesa
{
public int TipoDespesaId { get; set; }
[Display(Name = "Tipo de Despesa")]
[Required]
public string TipoDespesaNome { get; set; }
}
model3:
public class TipoPagamento
{
public int TipoPagamentoId { get; set; }
[Display(Name = "Tipo de Pagamento")]
[Required]
public string TipoPagamentoNome { get; set; }
}
myViewModel:
public class ViewModelDetalhes
{
public string TipoDespesa { get; set; }
public string TipoPagamento { get; set; }
public string Descricao { get; set; }
public decimal Valor { get; set; }
public DateTime Data { get; set; }
public string comentario { get; set; }
}
my Details:
public ActionResult Details(int? id)
{
var modelo = db.Despesas.Where(p => p.DespesaId == id).FirstOrDefault();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (modelo == null)
{
return HttpNotFound();
}
ViewModelDetalhes model = new ViewModelDetalhes()
{
TipoDespesa = modelo.TipoDespesa,
TipoPagamento = modelo.TipoPagamento,
Descricao = modelo.DespesaDescricao,
Valor = modelo.DespesaValor,
comentario = modelo.Comentario,
};
return View(model);
}
I dont know how i can get the values of TipoPagamento and TipoDespesa here should i do a include on the modelo? im a bit confused and need to know how to retrieve the values TipoPagamento and TipoDespesa associated with the main class Despesas.
Thanks

Your ViewModel
public class ViewModelDetalhes
{
public string TipoDespesa{ get; set; }
public string TipoPagamento { get; set; }
public string Descricao { get; set; }
public decimal Valor { get; set; }
public DateTime Data { get; set; }
public string comentario { get; set; }
}
If you want to lazy load make use of Virtual
public class Despesa
{
public int TipoDespesaId { get; set; }
public int DespesaId { get; set; }
[Display(Name = "Descrição da Despesa")]
[Required]
public string DespesaDescricao { get; set; }
[Display(Name = "Valor")]
[Required]
public decimal DespesaValor { get; set; }
public int TipoPagamentoId { get; set; }
[Display(Name = "Data")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
[Required]
public DateTime Data { get; set; }
public virtual TipoDespesa TipoDespesa { get; set; }
public virtual TipoPagamento TipoPagamento { get; set; }
[Display(Name = "Comentário")]
public string Comentario { get; set; }
}
You Detail ActionResult
public ActionResult Details(int? id)
{
var modelo = db.Despesas.Where(p => p.DespesaId == id).FirstOrDefault();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (modelo == null)
{
return HttpNotFound();
}
ViewModelDetalhes model = new ViewModelDetalhes()
{
TipoDespesa = modelo.TipoDespesa.TipoDespesaNome ,
TipoPagamento = modelo.TipoPagamento.TipoPagamentoNome,
Descricao = modelo.DespesaDescricao,
Valor = modelo.DespesaValor,
comentario = modelo.Comentario,
};
return View(model);
}
If you do not want to eager load use include. No need to add virtual to your POCO.
In your Detail ActionResult
public ActionResult Details(int? id)
{
var modelo = db.Despesas.Include("TipoDespesa").Include("TipoPagamento").Where(p => p.DespesaId == id).FirstOrDefault();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (modelo == null)
{
return HttpNotFound();
}
ViewModelDetalhes model = new ViewModelDetalhes()
{
TipoDespesa = modelo.TipoDespesa.TipoDespesaNome ,
TipoPagamento = modelo.TipoPagamento.TipoPagamentoNome,
Descricao = modelo.DespesaDescricao,
Valor = modelo.DespesaValor,
comentario = modelo.Comentario,
};
return View(model);
}
Read More Here: https://msdn.microsoft.com/en-gb/data/jj574232.aspx

Related

AutoMapper Many to Many relationship

I'm not sure where I'm going wrong here. I want to map my classes so that there aren't extra levels in the returned values.
Models (DTOs):
public class FilmViewModel
{
public FilmViewModel() { }
public int Id { get; set; }
[Required(ErrorMessage = "Naziv filma je obavezno polje.")]
public string Naziv { get; set; }
public string Opis { get; set; }
public string UrlFotografije { get; set; }
[RegularExpression(#"^(19|20)[\d]{2,2}$", ErrorMessage = "Godina mora biti u YYYY formatu.")]
public int Godina { get; set; }
public JezikEnum Jezik { get; set; }
public int Trajanje { get; set; }
public bool IsActive { get; set; }
public List<Licnost> Licnosti { get; set; }
}
public class LicnostViewModel
{
public LicnostViewModel() { }
public int Id { get; set; }
[Required]
public string ImePrezime { get; set; }
[Required]
public bool IsGlumac { get; set; }
[Required]
public bool IsRedatelj { get; set; }
public List<Film> Filmovi { get; set; }
}
Entities:
public class Film
{
[Key]
public int Id { get; set; }
[Required]
public string Naziv { get; set; }
public string Opis { get; set; }
public string UrlFotografije { get; set; }
[RegularExpression(#"^(19|20)[\d]{2,2}$")]
public int Godina { get; set; }
public JezikEnum Jezik { get; set; }
public bool IsActive { get; set; }
public int Trajanje { get; set; }
public List<FilmLicnost> Licnosti { get; set; }
}
public class Licnost
{
[Key]
public int Id { get; set; }
[Required]
public string ImePrezime { get; set; }
[Required]
public bool IsGlumac { get; set; }
[Required]
public bool IsRedatelj { get; set; }
public List<FilmLicnost> Filmovi { get; set; }
}
public class FilmLicnost
{
[Key]
public int Id { get; set; }
[ForeignKey(nameof(Licnost))]
public int LicnostId { get; set; }
public Licnost Licnost { get; set; }
[ForeignKey(nameof(Film))]
public int FilmId { get; set; }
public Film Film { get; set; }
}
Basically Swagger already shows me what I'm returning, but I want to avoid unnecessary nesting. It's marked in the image:
I want to say that I've been looking all over SO, AutoMapper documentation etc. No answer/example finds me the solution I need. I'm either missing a Model(DTO) somewhere or there is something major wrong with my logic.
Some example links that I tried are this and this
Also here are some links I tried to get information from: link1, link2
This is what I've tried so far:
CreateMap<FilmLicnost, LicnostViewModel>()
.ForMember(dest => dest.Filmovi, dest => dest.MapFrom(x => x.Film))
.AfterMap((source, destination) =>
{
if (destination?.Filmovi == null) return;
foreach (var temp in destination.Filmovi)
{
temp.Id = source.Film.Id;
temp.IsActive = source.Film.IsActive;
temp.Jezik = source.Film.Jezik;
temp.Naziv = source.Film.Naziv;
temp.Opis = source.Film.Opis;
temp.Godina = source.Film.Godina;
temp.Trajanje = source.Film.Trajanje;
temp.UrlFotografije = source.Film.UrlFotografije;
}
});
CreateMap<FilmLicnost, FilmViewModel>()
.ForMember(dest => dest.Licnosti, dest => dest.MapFrom(x => x.Licnost))
.AfterMap((source, destination) =>
{
if (destination?.Licnosti == null) return;
foreach (var temp in destination?.Licnosti)
{
temp.Id = source.Licnost.Id;
temp.ImePrezime = source.Licnost.ImePrezime;
temp.IsGlumac = source.Licnost.IsGlumac;
temp.IsRedatelj = source.Licnost.IsRedatelj;
}
});
Also this:
CreateMap<FilmLicnost, Film>()
.ForMember(dest => dest.Licnosti, dest => dest.Ignore());
CreateMap<FilmLicnost, Licnost>()
.ForMember(dest => dest.Filmovi, dest => dest.Ignore());
Note I have already defined the mapping for Entities:
CreateMap<Film, FilmViewModel>();
CreateMap<FilmViewModel, Film>();
CreateMap<Licnost, LicnostViewModel>();
CreateMap<LicnostViewModel, Licnost>();

assign list items to model properties

MODEL
namespace CG.MyPollSurveyAdmin.Models
{
public class CompletePollSurvey
{
public long PollSurveyID { get; set; }
public string Name { get; set; }
public List<OptionData> Options { get; set; }
public List<QuestionData> QuestionDetails { get; set; }
}
public class QuestionData
{
public string QuestionName { get; set; }
public long QuestionID { get; set; }
public int OptionID { get; set; }
public string OptionType { get; set; }
public string Option_1 { get; set; }
public string Option_2 { get; set; }
public string Option_3 { get; set; }
public string Option_4 { get; set; }
public string Option_5 { get; set; }
}
}
CONTROLLER
private List<Question> GetQuestionsById(long PollSurveyId)
{
MemoryStream outMemoryStream = RESTFulServiceHelper.Instance.ExecuteGetMethod(Constants.Method_GetAllQuestions, Convert.ToString(Session[Constants.NTLoginID]));
DataContractJsonSerializer outDataContractJsonSerialize = new DataContractJsonSerializer(typeof(List<Question>));
List<Question> lstQuestions = outDataContractJsonSerialize.ReadObject(outMemoryStream) as List<Question>;
List<Question> question = lstQuestions.Where(p => p.PollSurveyID == PollSurveyId).ToList();
return question;
}
public ActionResult Help(long PollSurveyID=2)
{
if (Session[Constants.Session_IsAdmin] != null && Convert.ToBoolean(Session[Constants.Session_IsAdmin]))
{
CompletePollSurvey completePollSurvey = new CompletePollSurvey();
List<Question> question = GetQuestionsById(Convert.ToInt64(PollSurveyID));
return View(completePollSurvey);
}
else
{
return RedirectToAction("Login");
}
}
Here is the model and controller of my program. Till now I'm getting All the questions for poll id=2 but I'm having difficulty in retrieving element from Question List and assign it to Model List elements(or list to list assignment).
For e.g I have 5 questions for Poll=2 and in each question there are 5 options

Automapper with nested entity not working

I have two classes which are mentioned below. I am trying to map those through Auto Mapper but it is not working.
public class VMTemplates
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
public System.DateTime TimeStamp { get; set; }
public virtual ICollection<VMTemplateGroup> VMTemplateGroup { get; set; }
}
public VMTemplateViewModel()
{
VMTemplateGroup = new List<VMTemplateGroupViewModel>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
[Required(ErrorMessage = "Please Upload File")]
[Display(Name = "Upload File")]
[ValidateFile]
public HttpPostedFileBase TemplateUpload { get; set; }
public System.DateTime TimeStamp { get; set; }
public List<VMTemplateGroupViewModel> VMTemplateGroup { get; set; }
I am using this code to map them
confi.CreateMap<VMTemplateViewModel, VMTemplates>().ReverseMap();
confi.CreateMap<VMTemplateGroupViewModel, VMTemplateGroup>().ReverseMap();
calling code
public VMTemplates GetVMTemplateById(int id)
{
return DataContext.VMTemplates.Include("VMTemplateGroup").Where(a => a.Id == id).FirstOrDefault();
}
This is where exception happens. I get stack overflow exception
public VMTemplateViewModel GetVMTemplateById(int templateId)
{
var result = _vmTemplateRepository.GetVMTemplateById(templateId);
return _autoMapperService.MapEntity<VMTemplateViewModel>(result);
}

MVC model value becomes null on post back

I am getting null value for the model on postback.I am not able to find out where I am going wrong.I have seen similar questions but couldn't find any solution yet.
Here is my code:
Controller:
public ActionResult ContactUpdate(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string[] testsplit = id.Split(',');
List<int> intTest = new List<int>();
foreach (string s in testsplit)
intTest.Add(int.Parse(s));
ObjectParameter ObjParam = new ObjectParameter("ErrorCode", 0);
var cont = db.spErrorContactGet(365, ObjParam);
var ToBeUpdated = (from contacts in cont
where intTest.Contains(contacts.ResponseID)
select contacts);
IEnumerable<spErrorContactGet_Result> Update = ToBeUpdated.ToList();
return View(Update);
}
[HttpPost]
public ActionResult ContactUpdate(List<spErrorContactGet_Result> Res)
{
if (Res == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do something
// redirect to another view
}
Here is the model class:
public class spErrorContactGet_Result
{
public int ResponseID { get; set; }
public string ContactAlchemyMessage { get; set; }
public string ContactTeamAlchemyMessage { get; set; }
public string ContactElectronicAddressAlchemyMessage { get; set; }
public string ContactAccountAlchemyMessage { get; set; }
public string CRMContactID { get; set; }
public string InfluenceLevel { get; set; }
public string JobRole { get; set; }
public string Department { get; set; }
public string DepartmentName { get; set; }
public string MobilePhone { get; set; }
public string Email { get; set; }
public string Suffix { get; set; }
public string FaxNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string JobTitle { get; set; }
public string HonorablePrefix { get; set; }
public string Prefix { get; set; }
public string ContactAuthPhoneId { get; set; }
public string ContactAuthDmailId { get; set; }
public string ContactAuthEmailId { get; set; }
public string AllowFax { get; set; }
public string PartnerContactAuthPhoneID { get; set; }
public string PartnerContactAuthDmailID { get; set; }
public string PartnerContactAuthEmailID { get; set; }
public string PrivacyStatementReviewed { get; set; }
public string PreferredLanguage { get; set; }
public string IndWorkPhone { get; set; }
public string FullNamePronunciation { get; set; }
public string CRMOwner { get; set; }
public string KeyContact { get; set; }
public string MarketingAudience { get; set; }
public bool IsSelected { get; set; }
}
}
I am unable to post the view in the right format.
It is likely that structure of your view differs from one that is of your model, they must syntactically match. If you would post your view it could help. BTW there is no 'Postback' in MVC

Model Binder in ASP.Net MVC 3 is not working

I am having a problem to bind the data sent with the model.
What I would like to bind is the OrderStatus that even if I pass it 10 it is always turned into 0.
I don't know why. I made this part bold to make it easier to detect in code:
Data sent as JSON:
{"CustomerOrderHeader":{"OrderNumber":"5",
"PartnerName":"BLI",
"Reference":"",
"ShippingDate":"10/152011",
"OrderStatusName":"Approved",
"CustomerOrderHeader.OrderStatus":"10",
"TotalAmount":"16.00",
"CustomerOrderHeader.CurrencyId":"0",
"CustomerOrderHeader.LanguageId":"0",
"DaLine1":"",
"DaLine2":"",
"DaCity":"",
"DaPostalCode":"",
"DaState":"",
"DaCountry":"",
"BaLine1":"",
"BaLine2":"",
"BaCity":"",
"BaPostalCode":"",
"BaState":"",
"BaCountry":"",
"Notes":""},
"CustomerOrderLines":[{"Id":214,"Num":10,"PartNumber":"dasdasd","Description":"dadadasd","OrderedQty":4,"UoM":"inteee","SalesPrice":null,"Amount":16,"LineStatus":10,"ConfirmedShippingDate":null,"ReservedQty":0,"DeliveredQty":0,"RemainingQty":4}]}
The method signature:
[HttpPost]
public JsonResult SaveOrUpdateOrderLines( CustomerOrderModel customerOrderModel )
and the model:
public class CustomerOrderModel
{
public CustomerOrderModel()
{
this.CustomerOrderLines = new List<CustomerOrderLineModel>();
this.CustomerOrderHeader = new CustomerOrderHeaderModel();
}
public CustomerOrderHeaderModel CustomerOrderHeader
{ get; set; }
public List<CustomerOrderLineModel> CustomerOrderLines
{ get; set; }
}
Customer Order List Model:
public class CustomerOrderLineModel
{
public CustomerOrderLineModel()
{
}
//TODO: Uncomment it
public long Id { get; set; }
[Required]
public String Num
{
get;
set;
}
//[ExistsOrEmptyPartNum(ErrorMessage = "The Part Number doesn't exist")]
//[Required]
[ExistInventoryPartNumOrNullAttribute]
public String PartNumber { get; set; }
public String Description { get; set; }
[Numeric(ErrorMessage = "Should be a number")]
[Min(0, ErrorMessage = "The number should be greater than zero")]
[IsTheSameTypeOfUOM("UnitOfMeasureId")]
public String OrderedQty { get; set; }
public String UoM { get; set; }
public long? UnitOfMeasureId { get; set; }
[Numeric(ErrorMessage = "Should be a number")]
public String SalesPrice { get; set; }
//[Numeric(ErrorMessage = "Should be a number")]
//[Min(0, ErrorMessage = "The number should be greater than zero")]
public String Amount { get; set; }
public String LineStatus { get; set; }
private int? _lineStatusNum;
public int? LineStatusNum
{
get
{
if (this.LineStatus == "Draft")
{
_lineStatusNum = 0;
return _lineStatusNum;
}
_lineStatusNum = null;
return null;
}
set
{
if (value == 0)
{
_lineStatusNum = value;
this.LineStatus = "Draft";
}
if (value == 10)
{
_lineStatusNum = value;
this.LineStatus = "Approved";
}
}
}
public DateTime? ConfirmedShippingDate { get; set; }
[Numeric(ErrorMessage = "Should be a number")]
public String ReservedQty { get; set; }
[Numeric(ErrorMessage = "Should be a number")]
public String DeliveredQty { get; set; }
[Numeric(ErrorMessage = "Should be a number")]
public String RemainingQty { get; set; }
public CustomerOrderHeader CustomerOrderHeader { get; set; }
}
Customer Order Header Model:
public class CustomerOrderHeaderModel
{
public class CustomDropDown
{
public CustomDropDown(object dataValue, string displayValue)
{
this.DataValue = dataValue;
this.DisplayValue = displayValue;
}
public object DataValue { get; set; }
public string DisplayValue { get; set; }
}
public CustomerOrderHeaderModel()
{
this.CurrencyId = 0;
this.TotalAmount = 0;
this.LanguageId = 0;
this.LanguageTypeList = new List<CustomDropDown>
{
new CustomDropDown(0, "English (Local Language)")
};
this.CurrencyTypeList = new List<CustomDropDown>
{
new CustomDropDown(0, "EUR (Local Currency)")
};
}
//public CustomerOrderHeaderModel(int orderStatus, long totalAmount)
//{
// this.OrderStatus = orderStatus;
// this.TotalAmount = totalAmount;
//}
#region Implementation of ICustomerOrderHeader
//public long CompanyId
//{ get; set; }
public string BillingAddress
{ get; set; }
public string ShippingAddress
{ get; set; }
[DisplayName("Customer name*:")]
[Required]
public string PartnerName
//public string CustomerName
{ get; set; }
[DisplayName("Order Number :")]
public long? OrderNumber
{ get; set; }
[DisplayName("Order Status :")]
public int OrderStatus
{ get; set; }
public string OrderStatusName
{ get
{
switch (OrderStatus)
{
case 0:
return "Draft";
case 10:
return "Approved";
case 20:
return "Ready for shipping";
case 30:
return "In Progress";
case 40:
return "Delivered";
case 50:
return "Closed";
case 60:
return "Cancelled";
default:
return "Undefinied";
}
}
}
[DisplayName("Shipping Date :")]
//[Range(typeof(DateTime), "01/01/1753", "12/31/9999", ErrorMessage = "Value for {0} must be between {1} and {2}")]
[DateRange]
//[DataType(DataType.Date, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy")]
//[Range(typeof(DateTime), "01/01/1753", "12/31/9999", ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy")]
public DateTime? ShippingDate
{ get; set; }
[DisplayName("Reference :")]
public string Reference
{ get; set; }
public Partner Partner
{ get; set; }
[DisplayName("Description :")]
public string Description
{ get; set; }
[DisplayName("Address Line 1 :")]
public string AddressLine1
{ get; set; }
[DisplayName("Address Line 2 :")]
public string AddressLine2
{ get; set; }
[DisplayName("City :")]
public string City
{ get; set; }
[DisplayName("Postal Code :")]
public string PostalCode
{ get; set; }
[DisplayName("State :")]
public string State
{ get; set; }
[DisplayName("Country :")]
public string Country
{ get; set; }
public bool IsDefaultda
{ get; set; }
public bool IsDefaultba
{ get; set; }
[DisplayName("Currency :")]
public long CurrencyId
{ get; set; }
[DisplayName("Language :")]
public long LanguageId
{ get; set; }
[DisplayName("Total Amount :")]
public decimal TotalAmount
{ get; set; }
[DisplayName("Address Line 1 :")]
public string DaLine1
{ get; set; }
[DisplayName("Address Line 2 :")]
public string DaLine2
{ get; set; }
[DisplayName("City :")]
public string DaCity
{ get; set; }
[DisplayName("Postal Code :")]
public string DaPostalCode
{ get; set; }
[DisplayName("State :")]
public string DaState
{ get; set; }
[DisplayName("Country :")]
public string DaCountry
{ get; set; }
[DisplayName("Address Line 1 :")]
public string BaLine1
{ get; set; }
[DisplayName("Address Line 2 :")]
public string BaLine2
{ get; set; }
[DisplayName("City :")]
public string BaCity
{ get; set; }
[DisplayName("Postal Code :")]
public string BaPostalCode
{ get; set; }
[DisplayName("State :")]
public string BaState
{ get; set; }
[DisplayName("Country :")]
public string BaCountry
{ get; set; }
[DisplayName("Notes :")]
public string Notes
{ get; set; }
public List<CustomDropDown> CurrencyTypeList { get; set; }
public List<CustomDropDown> LanguageTypeList { get; set; }
public List<CustomDropDown> OrderStatusTypeList { get; set; }
#endregion
}
At first glance the problem I see is that you are sending "OrderStatusName", but that property only has a get function and not a set.
I haven't examined the rest of the code or tested this; but if you don't have a SET for OrderStatusName, it won't work.
You could either send in the OrderStates (which has both get; set;), or implement the set to the OrderStatusName, which I wouldn't recommend as is not good practice.
Hope this helps,
-covo

Resources