How to check the value passed into the dictionary [duplicate] - c#

This question already has answers here:
The model item passed into the dictionary is of type .. but this dictionary requires a model item of type
(7 answers)
Closed 3 years ago.
The details are being fetched in the controller correctly but value passed in the view is incorrect. Therefore I am getting the following error:
The model item passed into the dictionary is of type 'System.Int64', but this >dictionary requires a model item of type >'estatebranch.ViewModels.RentRegisterViewModel'
My controller has following action method
public ActionResult RentRegister(int propertyId)
{
try
{
using (estatebranchEntities db = new estatebranchEntities())
{
RentRegisterViewModel objRentRegister = new RentRegisterViewModel();
objRentRegister.balance = db.PropertyDetails.Where(m => m.propertyid == propertyId).Select(m => m.balance).SingleOrDefault();
return View(objRentRegister.balance);
}
}
catch (Exception)
{
throw;
}
}
My View model is as follow:
public class RentRegisterViewModel
{
public int recordid { get; set; }
public int propertyid { get; set; }
public int month { get; set; }
public int year { get; set; }
public long amountpaid { get; set; }
public System.DateTime paymentdate { get; set; }
public long interest { get; set; }
public Nullable<long> balance { get; set; }
public virtual PropertyDetail PropertyDetail { get; set; }
}

try changing this line:
return View(objRentRegister);

Related

How to pass different types of html heplers data to controller

I got this models in my project:
public class Question
{
public int Id { get; set; }
public string Text { get; set; }
public QuestionType Type { get; set; }
public QuestionsTheme Theme { get; set; }
public string AnswerData { get; set; }
}
public class QuestionType
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public TestStatus Status { get; set; }
public DateTime CreationDate { get; set; }
public DateTime Deadline { get; set; }
public DateTime FinishDate { get; set; }
public string CreatorLogin { get; set; }
public TestTheme Theme { get; set; }
}
public class QuestionsInTest
{
public int Id { get; set; }
public Test Test { get; set; }
public Question Question { get; set; }
}
public class AnswersOption
{
public int Id { get; set; }
public Question Question { get; set; }
public string Text { get; set; }
}
public class UserAnswer
{
public int Id { get; set; }
public string UserId { get; set; }
public Question Question { get; set; }
public Test Test { get; set; }
public string Data { get; set; }
public AnswerResult Result { get; set; }
}
Action on controller:
public ActionResult TestPage(int id, bool? isStarted)
{
var test = _testService.GetTest(id); //get test by Id
var qsts = _testService.GetQuestionsInTest(test); // get all questions in test
if (isStarted==null)
{
ViewBag.Qstns = qsts;
return View(test);
}
if (isStarted==true)
test.Status = Models.Enums.TestStatus.InProgress;
_testService.Update(test);
ViewBag.Qstns = qsts;
ViewBag.QstOptions = _answerService.GetAnswersOptions(qsts);
//get all answer options for every question
return View(test);
}
TestPage view render depends on test.Status. If Status is "inProgress", Test page with questions renders. This part is that im intrerested in.
...
...
...
if (Model.Status == OnlineTestingProject.Models.Enums.TestStatus.NotStarted)
{
<h1>Test is not started</h1>
<b>Creation date: </b>
<b>#Model.CreationDate</b>
<b>Test creator: </b>
<b>#Model.CreatorLogin</b>
using (Html.BeginForm("TestPage", "Student", FormMethod.Post))
{
#Html.Hidden("id", #Model.Id)
#Html.Hidden("isStarted", true)
<input type="submit" value="Begin test" />
}
}
if (Model.Status == OnlineTestingProject.Models.Enums.TestStatus.InProgress)
{
int i = 0;
<h1>les gooo</h1>
foreach (Question qst in ViewBag.Qstns)
{
<div>
#{
<b>Question number : #i</b>
<p>#qst.Text</p>
foreach (AnswersOption opt in ViewBag.QstOptions)
{
if (opt.Question == qst)
{
if (opt.Question.Type.Name == "Single")
{
...
}
if (opt.Question.Type.Name == "Multi")
{
...
}
...
}
}
}
<hr />
</div>
i++;
}
}
}
The idea is:
User open a Test Page. Test has a set of questions. Every question has specific type (like usual with one right answer, with multiple right answers, question with typing field end so on). Every question also has a set of answers variants. Questions with one right answer will have radio buttons for options, qustions with multiple options will have comboboxes, input for amother and so on. User should fill the answer and on sumbit button (e. g. Finish test) all answers given by user should be compared with right answer.
The question is:
How to organize it on view side. And how to agregate it on controller side.
I got some thoughts about one big modelView or dictionaries but my brain in already melting so i would be glad to get some kick in the right direction.
UPD. I know one way (or the only way) to do it is to fill ViewModel. But i have no idea how this model should looks like. Is the best way to create some ViewModel and if it is, then how to store all my answers and its options and how to compare given answer with right one properly

How to create instance of nested class? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
I have a viewmodel and it contains two viewmodel in ReaderBorrowViewModel, I'm not sure it's best practice but it makes sense to me. In GetReaderDetailModel method i got borrows from db. After every borrowed book i tried to get data for ReaderDetailViewModel which contains BookStateModel and BookViewModel.Getting all borrowed books i added to list in ReaderBorrowModel to send it client.I got Object reference not set to an instance of an object while i creating an instance of ReaderBorrowModel. What's my fault ?
public class BookStateViewModel
{
public int BookStateKey { get; set; }
public string Name { get; set; }
}
public class BookViewModel
{
public int BookKey { get; set; }
public string ISBN { get; set; }
public string Name { get; set; }
public string Author { get; set; }
}
public class ReaderBorrowModel
{
public int BorrowKey { get; set; }
public BookViewModel Book { get; set; }
public BookStateViewModel BookState { get; set; }
}
public class ReaderDetailViewModel
{
public MemberViewModel Member { get; set; }
public List<ReaderBorrowModel> Borrows { get; set; }
}
public async Task<ReaderDetailViewModel> GetReaderDetailModel(int memberKey)
{
ReaderDetailViewModel result = new ReaderDetailViewModel();
var borrows= borrowService.SelectIncludeMany(x => x.Member,k=>k.Book, d=>d.BookState).Where(x=>x.MemberKey== memberKey);
var member= borrows.Select(x => x.Member);
try
{
borrows.ToList().ForEach(o =>
{
var borrow = new ReaderBorrowModel
{
BorrowKey = o.BorrowKey,
Book = new BookViewModel
{
BookKey = o.Book.BookKey ,
Name = o.Book.Name ,
ISBN = o.Book.ISBN ,
Author = o.Book.Author.Name
},
BookState = new BookStateViewModel
{
BookState Key = o.BookState Key,
Name= o.BookState.Name
}
};
result.Borrows.Add(odunc);
});
}
catch (Exception ex)
{
throw ex;
}
return result;
}
You have not initialized the property to a new list. Try the below snippet. Once the list is set to a new list, you don't get null reference exception
public class ReaderDetailViewModel
{
public ReaderDetailViewModel() {
Borrows = new List<ReaderBorrowModel>();
}
public MemberViewModel Member { get; set; }
public List<ReaderBorrowModel> Borrows { get; set; }
}
Note
As a good practice, you can always initialize the list / dictionary etc to a new list or new dictionary etc so that you don't run into null reference exceptions.

Create controller "Object reference not set to an instance of an object" [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I have a create controller on ASP Net core application, that creates a new FinancePaymentReceipt.
The controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("FinanceInvoiceID,Payment_Reference_Number,FinancePaymentTypeID,Payment_Amount,Payment_Date")] FinancePaymentReceipt financePaymentReceipt)
{
var invoice = await _context.FinanceInvoices
.Include(fi=>fi.FinanceDailyClaim)
.ThenInclude(fdc=>fdc.Department)
.Where(ss=>ss.FinanceInvoiceID==financePaymentReceipt.FinanceInvoiceID)
.SingleOrDefaultAsync();
if (invoice == null)
{
return NotFound();
}
if (ModelState.IsValid)
{
financePaymentReceipt.PaymentReceiptNumber = await _numberSequence.GetNumberSequence("RECPT", invoice.FinanceDailyClaim.Department.Department_Code, 'C');
_context.Add(financePaymentReceipt);
await _context.AddAsync(new FinanceAccountSatement
{
FinancePaymentReceiptID = financePaymentReceipt.FinancePaymentReceiptID,
Activity_Date = financePaymentReceipt.Date_Captured
});
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
The model
public class FinancePaymentReceipt
{
private decimal _Payment_Amount;
[Key]
public int FinancePaymentReceiptID { get; set; }
[Display(Name = "Payment Receive Number")]
public string PaymentReceiptNumber { get; set; }
[Display(Name = "Invoice Number")]
public int FinanceInvoiceID { get; set; }
[Display(Name = "Payment Reference No")]
public string Payment_Reference_Number { get; set; }
[Display(Name = "Payment Type")]
public int FinancePaymentTypeID { get; set; }
public decimal Payment_Amount
{
get { return _Payment_Amount; }
set
{
_Payment_Amount = -Math.Abs(value);
}
}
public string Description
{
get
{
return $"Payment for {FinanceInvoice.Invoice_Number} Thank You";
}
}
public DateTime Payment_Date { get; set; }
public string Captured_By { get; set; }
public DateTime Date_Captured { get; set; } = DateTime.Now;
public FinanceInvoice FinanceInvoice { get; set; }
public FinancePaymentType FinancePaymentType { get; set; }
}
From the FinancePaymentReceipt model above i have a property Description and it has only the get accesor and retrieves the Invoice number from the FinanceInvoice model.
But the problem is that when i create it, tries to get the Description before saving the model to the database, In fact if I put a break point before at the start of the create controller it does not even hit.
i just get the error Object reference not set to an instance of an object when i click the 'create button`
Is there a way around this issue?
One solution is just to return null for the Description if FinanceInvoice hasn't been set yet. Something like this:
public string Description
{
get
{
return FinanceInvoice == null
? null
: $"Payment for {FinanceInvoice.Invoice_Number} Thank You";
}
}
I'm using C#'s conditional operater there.

Entity Framework Error: Specified Include Path Is Not Valid for Virtual Entity [duplicate]

This question already has answers here:
A specified Include path is not valid. The EntityType does not declare a navigation property with the name *
(5 answers)
Closed 3 years ago.
I am encountering an error to the effect of "A specified Include path is not valid. The EntityType 'MyCMS.DAL.SiteSettings' does not declare a navigation property with the name 'SiteSettingOptions'."
I have read quite a few posts about this issue but all of the research I have done pertains to ICollections and not for properties that are classes.
Here is where I am and could use your help resolving the issues.
[Table("SiteSettingsBridge")]
[DataContract]
public partial class SiteSettings
{
[Key]
[DataMember]
public int SiteSettingsBridgeID { get; set; }
[DataMember]
public int SiteID { get; set; }
[DataMember]
public int SiteSettingOptionID { get; set; }
[DataMember]
public virtual SiteSettingOptions SiteSettingOption { get; set; }
[DataMember]
[StringLength(500)]
public string Value { get; set; }
public SiteSettings()
{
SiteSettingsBridgeID = 0;
SiteID = 0;
SiteSettingOptionID = 0;
Value = "";
}
}
[DataContract]
public partial class SiteSettingOptions
{
[Key]
[DataMember]
public int SiteSettingOptionID { get; set; }
[DataMember]
public string SettingsGroup { get; set; }
[DataMember]
[StringLength(100)]
public string Name { get; set; }
[DataMember]
[StringLength(500)]
public string DefaultValue { get; set; }
[DataMember]
public SettingType Type { get; set; }
public enum SettingType
{
String = 1,
Bool = 2,
Integer = 3
}
public SiteSettingOptions()
{
SiteSettingOptionID = 0;
SettingsGroup = string.Empty;
Name = string.Empty;
DefaultValue = string.Empty;
Type = SiteSettingOptions.SettingType.String;
}
}
and then in my DAL project, I am attempting to add an Include to the context query like this
public static List<Contracts.Sites.SiteSettings> GetBySiteID(int SiteID)
{
using (CMSContext cntx = new CMSContext())
{
///OMITTED FOR BREVITY
return cntx.SiteSettings.Include("SiteSettingOptions").Where(i => i.SiteID == SiteID).ToList();
}
}
When I compile and run, I am receiving the above error.
To answer a few questions up front, I am not using LazyLoading and I am not doing anything on model create.
Yes, I am brand new to EF. This is my first app.
Thanks Ben...
Your property is called SiteSettingOption (no s) but you are trying to Include("SiteSettingOptions") (notice the final s). Remove the last s. You can avoid this by using the Include extension that uses lambdas rather than strings this would be something like Include(x => x.SiteSettingOption)

Value Cannot be null calculated model properties MVC 5 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have an model in my MVC application that contains som properties and som calculated properties. When i try to POST a new object of the model to database i get an error that my calculated properties cannot be null.
Here is my model:
public class OrderItem
{
public int orderItemId { get; set; }
[DataType(DataType.MultilineText)]
public string orderItemDescr { get; set; }
public string orderItemText { get; set; }
public double orderItemFixeedPrice { get; set; }
public virtual Order orderItemOrder { get; set; }
public virtual OrderItemType orderItemType { get; set; }
public virtual ICollection<Time> orderItemTime { get; set; }
public virtual ICollection<Material> orderItemMaterial { get; set; }
public OrderItem ()
{ }
public OrderItem (Order order)
{
this.orderItemOrder = order;
}
public string orderItemTypeDescr
{
get
{
return (this.orderItemType.orderItemTypeNumber.ToString() + " - " + orderItemDescr);
}
}
public double orderItemMaterialSum
{
get
{
return orderItemMaterial.Sum(m => m.materialItmPrice * m.materialItem);
}
}
public double orderItemTimeCount
{
get
{
return orderItemTime.Sum(t => t.timeItem);
}
}
public double orderItemTimeSum
{
get
{
return orderItemTime.Sum(t => t.timePrice * t.timeItem);
}
}
public double orderItemSum
{
get
{
return orderItemTimeSum + orderItemMaterialSum;
}
}
}
Error shows on properties: orderItemMaterialSum, orderItemTimeCount, orderItemTimeSum
these properties is only calculated as you seen and should not have values.
The problem comes only when i create an objekt and post it to database.
The reason for the error is that your properties in question are doubles and thus cannot be null. Three ways come to mind to address the problem:
Convert the properties in question to methods and re-factor your code
as necesesary.
Use a view model which only includes the properties you need (recommended)
Use the bind attribute to specify how binding is to be done when the model is posted (link)
Best practice is to use view models. Your view model might look something like the following:
public class OrderItemViewModel
{
public int orderItemId { get; set; }
[DataType(DataType.MultilineText)]
public string orderItemDescr { get; set; }
public string orderItemText { get; set; }
public double orderItemFixeedPrice { get; set; }
public virtual Order orderItemOrder { get; set; }
public virtual OrderItemType orderItemType { get; set; }
public virtual ICollection<Time> orderItemTime { get; set; }
public virtual ICollection<Material> orderItemMaterial { get; set; }
public string orderItemTypeDescr
{
get
{
return this.orderItemType.orderItemTypeNumber.ToString() + " - " + this.orderItemDescr;
}
}
}
Does this help?

Categories