I have two models as shown below:
One:
[Validator(typeof(BlogPostValidator))]
public partial class BlogPostModel : BaseNopEntityModel
{
public BlogPostModel()
{
Tags = new List<string>();
Comments = new List<BlogCommentModel>();
AddNewComment = new AddBlogCommentModel();
}
public string SeName { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public bool AllowComments { get; set; }
public int NumberOfComments { get; set; }
public DateTime CreatedOn { get; set; }
public IList<string> Tags { get; set; }
public IList<BlogCommentModel> Comments { get; set; }
public AddBlogCommentModel AddNewComment { get; set; }
public BlogCommentModel blogcommentmodel { get; set; }
}
two:
public partial class BlogCommentModel : BaseNopEntityModel
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerAvatarUrl { get; set; }
public string CommentText { get; set; }
public DateTime CreatedOn { get; set; }
public bool AllowViewingProfiles { get; set; }
public int CommentParentID { get; set; }
public IList<BlogComment> ChildCommentList { get; set; }//netra
}
I want to make use of ChildCommentList from BlogCommentModel to show nested comments.
My View:
#model BlogPostModel
#using Nop.Web.Models.Blogs;
#if (Model.AllowComments)
{
<div class="clear">
</div>
<fieldset class="new-comment" id="addcomment">
<legend class="title">#T("Blog.Comments.LeaveYourComment")</legend>
#using (Html.BeginForm())
{
<div>
<div class="message-error">#Html.ValidationSummary(true)</div>
#{
string result = TempData["nop.blog.addcomment.result"] as string;
}
#if (!String.IsNullOrEmpty(result))
{
<div class="result">#result</div>
}
<div class="forms-box">
<div class="inputs">
#Html.LabelFor(model => model.AddNewComment.CommentText)
<div class="input-box">
#Html.TextAreaFor(model => model.AddNewComment.CommentText, new { #class = "comment-text" })
</div>
#Html.ValidationMessageFor(model => model.AddNewComment.CommentText)
</div>
#if (Model.AddNewComment.DisplayCaptcha)
{
<div class="captcha-box">
#Html.Raw(Html.GenerateCaptcha())
</div>
<div class="clear">
</div>
}
</div>
<div class="clear">
</div>
<div class="buttons">
<input type="submit" name="add-comment" class="button-1 blog-post-add-comment-button" value="#T("Blog.Comments.SubmitButton")" />
</div>
</div>
}
</fieldset>
if (Model.Comments.Count > 0)
{
<div class="clear">
</div>
<div class="comment-list">
<div class="title">
#T("Blog.Comments")
</div>
<div class="clear">
</div>
#foreach (var comment in Model.Comments)
{
<div class="blog-comment">
<div class="comment-info">
<div class="user-info">
#if (comment.AllowViewingProfiles)
{
#(comment.CustomerName)
}
else
{
<span class="username">#(comment.CustomerName)</span>
}
<div class="avatar">
#if (!String.IsNullOrEmpty(comment.CustomerAvatarUrl))
{
<img src="#(comment.CustomerAvatarUrl)" class="avatar-img" title="avatar" alt="avatar" />
}
</div>
</div>
</div>
<div class="comment-content">
<div class="comment-time">
#T("Blog.Comments.CreatedOn"): <span class="stat-value">#comment.CreatedOn.ToString("g")</span>
</div>
<div class="comment-body">
#Html.Raw(Nop.Core.Html.HtmlHelper.FormatText(comment.CommentText, false, true, false, false, false, false))
</div>
</div>
#Html.Widget("blogpost_page_inside_comment")
</div>
<div class="clear">
</div>
<div>
#foreach(var childcomments in Model.blogcommentmodel.ChildCommentList)
{
#Html.Raw(Nop.Core.Html.HtmlHelper.FormatText(childcomments.CommentText, false, true, false, false, false, false))
}
</div>
}
<div class="buttons">
<input type="submit" id="replyto" name="reply-comment" class="button-1 blog-post-add-comment-button" value="#T("Blog.Comments.ReplyButton")" />
</div>
</div>
}
}
Error occurred on :
#foreach(var childcomments in Model.blogcommentmodel.ChildCommentList)
{
#Html.Raw(Nop.Core.Html.HtmlHelper.FormatText(childcomments.CommentText, false, true, false, false, false, false))
}
</div>
}
NullReferenceException was unhandled by usercode -{"Object reference not set to an instance of an object."}
My controller code for ActionResult:
public ActionResult BlogPost(int blogPostId)
{
if (!_blogSettings.Enabled)
return RedirectToRoute("HomePage");
var blogPost = _blogService.GetBlogPostById(blogPostId);
if (blogPost == null ||
(blogPost.StartDateUtc.HasValue && blogPost.StartDateUtc.Value >= DateTime.UtcNow) ||
(blogPost.EndDateUtc.HasValue && blogPost.EndDateUtc.Value <= DateTime.UtcNow))
return RedirectToRoute("HomePage");
var model = new BlogPostModel();
**PrepareBlogPostModel(model, blogPost, true);**
return View(model);
}
Below method called in above ActionResult:
[NonAction]
protected void PrepareBlogPostModel(BlogPostModel model, BlogPost blogPost, bool prepareComments)
{
if (blogPost == null)
throw new ArgumentNullException("blogPost");
if (model == null)
throw new ArgumentNullException("model");
model.Id = blogPost.Id;
model.SeName = blogPost.GetSeName();
model.Title = blogPost.Title;
model.Body = blogPost.Body;
model.AllowComments = blogPost.AllowComments;
model.CreatedOn = _dateTimeHelper.ConvertToUserTime(blogPost.CreatedOnUtc, DateTimeKind.Utc);
model.Tags = blogPost.ParseTags().ToList();
model.NumberOfComments = blogPost.ApprovedCommentCount;
model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage;
if (prepareComments)
{
// var blogchildcomment = _blogService.GetAllChildComments();
var blogComments = blogPost.BlogComments.Where(pr => pr.IsApproved).OrderBy(pr => pr.CreatedOnUtc);
foreach (var bc in blogComments)
{
var commentModel = new BlogCommentModel()
{
Id = bc.Id,
CustomerId = bc.CustomerId,
CustomerName = bc.Customer.FormatUserName(),
CommentText = bc.CommentText,
CreatedOn = _dateTimeHelper.ConvertToUserTime(bc.CreatedOnUtc, DateTimeKind.Utc),
AllowViewingProfiles = _customerSettings.AllowViewingProfiles && bc.Customer != null && !bc.Customer.IsGuest(),
CommentParentID = bc.CommentParentID,//Netra
};
//Netra
var comments = _blogService.GetBlogComments(bc.CommentParentID);
if (comments != null)
{
commentModel.ChildCommentList = new List<BlogComment>();
foreach (var cmnt in comments)
{
commentModel.ChildCommentList.Add(cmnt);
}
}
if (_customerSettings.AllowCustomersToUploadAvatars)
{
var customer = bc.Customer;
string avatarUrl = _pictureService.GetPictureUrl(customer.GetAttribute<int>(SystemCustomerAttributeNames.AvatarPictureId), _mediaSettings.AvatarPictureSize, false);
if (String.IsNullOrEmpty(avatarUrl) && _customerSettings.DefaultAvatarEnabled)
avatarUrl = _pictureService.GetDefaultPictureUrl(_mediaSettings.AvatarPictureSize, PictureType.Avatar);
commentModel.CustomerAvatarUrl = avatarUrl;
}
model.Comments.Add(commentModel);
}
}
}
BlogComment is class which describes the properties.
public partial class BlogComment : CustomerContent
{
/// <summary>
/// Gets or sets the comment text
/// </summary>
public virtual string CommentText { get; set; }
/// <summary>
/// Gets or sets the blog post identifier
/// </summary>
public virtual int BlogPostId { get; set; }
/// <summary>
/// Gets or sets the blog post
/// </summary>
public virtual BlogPost BlogPost { get; set; }
public virtual int CommentParentID { get; set; } //netra
}
So you have a null somewhere - you need to find out what's null and make it so it's not null; or change the Razor code to something like:
#if(Model.blogcommentmodel != null && Model.blogcommentmodel.ChildCommentList != null)
{
#* original #foreach statement here *#
}
My first guess would be that you need to create a default constructor for your model. In the constructor, set ChildCommentList = new List<BlogComment>();.
It looks like you didn't set that in your Controller, which the way that you have your Model set up, would cause ChildCommentList to still be null. With that default constructor, you won't have to worry about your code breaking like this if you miss setting it somewhere.
To answer wnetra's comment, the constructor is on the BlogcommentModel class. So you'll need something like this:
public class BlogcommentModel {
/* All of the property declarations */
public IList<BlogComment> ChildCommentList { get; set; }
/* Constructor for the BlogcommentModel class */
public BlogcommentModel() {
ChildcommentList = new List<BlogComment>();
}
}
Any reference objects should always be instantiated inside a default constructor to ensure they won't be null when trying to reference them in code.
Also see Andras' answer with regard to always doing != null when trying to reference reference objects in your code.
I have removed following code from BlogCommenmodel :
//public int CommentParentID { get; set; }
//public IList<BlogComment> ChildCommentList { get; set; }//netra
//public BlogCommentModel()
//{
// ChildCommentList = new List<BlogComment>();
//}
and introduced in BlogPostModel
[Validator(typeof(BlogPostValidator))]
public partial class BlogPostModel : BaseNopEntityModel
{
public BlogPostModel()
{
Tags = new List<string>();
Comments = new List<BlogCommentModel>();
AddNewComment = new AddBlogCommentModel();
ChildCommentList = new List<BlogComment>();
}
public string SeName { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public bool AllowComments { get; set; }
public int NumberOfComments { get; set; }
public DateTime CreatedOn { get; set; }
public IList<string> Tags { get; set; }
public IList<BlogCommentModel> Comments { get; set; }
public AddBlogCommentModel AddNewComment { get; set; }
//Netra
public int CommentParentID { get; set; }
public IList<BlogComment> ChildCommentList { get; set; }//netra
// public BlogCommentModel blogcommentmodel { get; set; }
}
IN View:
<div>
#if (Model.ChildCommentList != null)
{
foreach (var childcomments in Model.ChildCommentList)
{
#Html.Raw(Nop.Core.Html.HtmlHelper.FormatText(childcomments.CommentText, false, true, false, false, false, false))
}
}
</div>
Related
I have a problem when it comes to updating a new order (in an array of complex object)
I apply the same Update Page with other object (Eg. Category) and the code worked on most case but this!
Any recommendations you may have will be welcomed and much appreciated! Thanks!
I have these 3 Entities:
public class Order
{
public int OrderId { get; set; }
public string Customer { get; set; }
public List<OrderItem> OrderItems { get; set; }
}
public class OrderItem
{
public int OrderItemId { get; set; }
public string Category { get; set; }
public int Quantity { get; set; }
}
public struct Category
{
public int CategoryId;
public string CategoryName;
}
On Razor Page (view):
<form method="POST">
<label for="orderid">OrderId:</label>
<input type="text" asp-for="order.OrderId" value="#Model.orderS.OrderId" />
<label for="customer">Customer:</label>
<input type="string" asp-for="order.Customer" value="#Model.HoaDonNH.orderS.OrderId" />
<table>
<tr>
<th>Category</th>
<th>Quantity</th>
</tr>
#for(int i = 0; i < 3; i++)
{
<tr>
<td>
<select asp-for="order.OrderItems[i].Category">
#foreach (Category c in Model.CategoryList)
{
<option value="#c.CategoryName">#c.CategoryName</option>
}
</select>
</td>
<td>
<input type="text" value="#Model.orderS.OrderItems[i].Quantity" asp-for="order.OrderItems[i].Quantity" />
</td>
</tr>
}
</table>
<input type="submit" value="Update" />
</form>
Services:
public static bool Update(Order o)
{
Order[] OrderList = ReadList();
for (int i = 0; i < OrderList.Length; i++)
{
if (OrderList[i].OrderId == hd.OrderId)
{
OrderList[i] = o;
Savelist(OrderList);
return true;
}
}
return false;
}
public static Order[] ReadList()
{
string filePath = "e:\\order.json";
StreamReader file = new StreamReader(filePath);
string json = file.ReadToEnd();
file.Close();
Order[] OrderList = JsonConvert.DeserializeObject<Order[]>(json);
return OrderList;
}
PageModel: (cshtml.cs)
public string Message;
public Order orderS;
public Category[] CategoryList;
[BindProperty(SupportsGet = true)]
public int Id { get; set; }
[BindProperty]
public Order order { get; set; }
public void OnGet()
{
if (Id > 0)
{
orderS = Services.ReadOrder(Id);
CategoryList = Services.ReadList();
}
else
{
Message += "Order ID is invalid";
}
}
public void OnPost()
{
HoaDonNH = Services.ReadOrder(Id);
OrderList = Services.ReadList();
bool result = Services.Update(order);
Message += "Successfully update your order!";
}
Note:
I have tested the Create, Read, Delete Page and they all worked!
There is no Error Message after hitting submit!
The specific order will be updated and save in the array in my json file after hitting submit.
I'm trying to come up with a Blazor implementation of using an array type model with multiple checkboxes.
Vue component:
<template>
<div>
<b-form-group label="Using sub-components:">
<b-form-checkbox-group id="checkbox-group-2" v-model="selected" name="flavour-2">
<b-form-checkbox value="orange">Orange</b-form-checkbox>
<b-form-checkbox value="apple">Apple</b-form-checkbox>
<b-form-checkbox value="pineapple">Pineapple</b-form-checkbox>
<b-form-checkbox value="grape">Grape</b-form-checkbox>
</b-form-checkbox-group>
</b-form-group>
<div>Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: [], // Must be an array reference!
}
}
}
</script>
Blazor component:
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="#id" name="#name" #onchange="#((ChangeEventArgs) => CheckedChanged(ChangeEventArgs, value))">
<label class="custom-control-label" for="#id">#label</label>
</div>
#code {
[Parameter]
public string id { get; set; }
[Parameter]
public string name { get; set; }
[Parameter]
public object value { get; set; }
[Parameter]
public List<object> model { get; set; }
[Parameter]
public EventCallback<List<object>> modelChanged { get; set; }
[Parameter]
public string label { get; set; }
protected override void OnInitialized()
{
base.OnInitialized();
}
protected void CheckedChanged(ChangeEventArgs args, object value)
{
if(!model.Any(i => i == value))
{
model.Add(value);
}
else
{
model.Remove(value);
}
}
}
Usage:
#foreach (string timezone in DistinctTimezones)
{
<BCheckbox #bind-model="#FilterTimezones" value="#timezone" label="#timezone" id="#(string.Format("timezone_{0}", timezone))" name="#(string.Format("timezone_{0}", timezone))" />
}
<p>Selected:</p>
#foreach(var timezone in FilterTimezones)
{
#timezone
}
#code {
protected List<string> DistinctTimezones { get; set; } = new List<string>{"Central", "Eastern"};
protected List<object> FilterTimezones { get; set; } = new List<object>();
}
When I check the checkboxes, the FilterTimezone object doesn't get updated with the values from checked checkboxes. Is this something that is already possible and I am overcomplicating it? I'm only aware of binding values to a non-collection type.
I'd do it like that (string is here just to simplify to get the idea)
CollectionCheckBox.razor
<input type="checkbox" #bind=isChecked />
#code
{
[Parameter]
public string Value { get; set; }
[Parameter]
public List<string> Model {get; set;}
private bool isChecked
{
get => Model.Any(el => el == Value);
set
{
if(value)
{
if(!Model.Any(el => el == Value) Model.Add(Value);
}
else
Model.Remove(Value);
}
}
}
Then in parent component you just do
<CollectionCheckBox Model="#Model", Value="Orange" />
<CollectionCheckBox Model="#Model", Value="Apple" />
<CollectionCheckBox Model="#Model", Value="Pineapple" />
<CollectionCheckBox Model="#Model", Value="Grape" />
#code
{
private List<string> Model = new List<string();
}
My Viewmodel (contains a number of submodels) is:
public class ViewModel
{
public IEnumerable<tblQuestion> DemoQuestions { get; set; }
public IEnumerable<tblQuestion> TechQuestions { get; set; }
public List<tblAnswer> DemoQ1Answers { get; set; }
public List<tblAnswer> DemoQ2Answers { get; set; }
public List<tblAnswer> TechAnswers { get; set; }
public string selectedAnswerIDforQ1 { get; set; }
public string selectedAnswerIDforQ2 { get; set; }
}
My tblAnswer model is like below:
public partial class tblAnswer
{
public int AnswerID { get; set; }
public Nullable<int> QuestionID { get; set; }
public string AnswerDescription { get; set; }
public string Q1Other { get; set; }
}
This is my view code:
#using (Html.BeginForm("Display", "Questionnaire", FormMethod.Post))
{
foreach (tblQuestion question in Model.DemoQuestions)
{
<p>#question.QuestionDescription</p>
#for (int i = 0; i < Model.DemoQ1Answers.Count(); i++)
{
if (question.QuestionID == 1)
{
<div class="col-md-4">
#Html.RadioButtonFor(m => Model.selectedAnswerIDforQ1, Model.DemoQ1Answers[i].AnswerID)
#Model.DemoQ1Answers[i].AnswerDescription
#Html.HiddenFor(m => Model.DemoQ1Answers[i].AnswerID)
#Html.HiddenFor(m => Model.DemoQ1Answers[i].AnswerDescription)
#if (Model.DemoQ1Answers[i].AnswerID == 4)
{
#Html.TextBoxFor(m => Model.DemoQ1Answers[i].Q1Other)
}
</div>
}
}
}
<input type="submit" value="Submit" />
}
When I press submit, my textbox value in the model is null. Means, mymodel.DemoQ1Answers[3].Q1Other is null. All other model values are bound with model values in the view except this one.
This is my controller:
[HttpPost]
public ActionResult Display(ViewModel mymodel)
{
foreach (var demoqstns in mymodel.DemoQuestions)
{
int AnswerSelected = 0;
string otherText = null;
if (qstnID == 1)
{
AnswerSelected = Convert.ToInt32(mymodel.selectedAnswerIDforQ1);
if (AnswerSelected == 4)
{
otherText = mymodel.DemoQ1Answers[3].Q1Other;
}
}
else if (qstnID == 2)
{
AnswerSelected = Convert.ToInt32(mymodel.selectedAnswerIDforQ2);
}
}
}
Please help.
you have to use for loop instated of foreach
for (var i = 0; i < Model.Orders.Count(); i++)
#Html.HiddenFor(x => Model.Orders[i].CustomerID)
the index value i appears in the lambda expression for each form element being generated by the loop, The TextBoxFor HtmlHelper is used, rather than the more general (and automagic) DisplayFor and EditorFor.
I have a Controller, View, and Model for an application I am taking over from someone else. The problem I'm having is that when the javascript submits the form, my model object in the Edit function of the Controller is not being filled with the values from the View, all fields are either null or 0. How can I get the object to be properly filled?
I have tried looking at Firebug, but I can't see anything that would indicate a problem. The string parameter id is correctly being passed in the URL, ex: firsttry.com/admin/distribution/edit/sanfran, where sanfran is the id string. Firebug is confirming that the javascript is correctly loaded when it would be called.
#section scripts
{
#Scripts.Render("~/bundles/qmmodules/admin/distribution")
}
DistributionController.cs
namespace JRI.QM.WebUI.Areas.Admin.Controllers
{
public class DistributionController : BaseAdminController
{
[HttpPost]
public ActionResult Edit(string id, DistributionViewModel model)
{
}
}
}
DistributionViewModel.cs
namespace JRI.QM.WebUI.Areas.Admin.Models.ViewModels
{
public class DistributionViewModel
{
public string name;
public string ipAddress;
public string description;
public Byte eyeDee;
public string destinationPath;
public List<JRI.DMP.BLL.Filter> filters;
}
}
Edit.cshtml
#model JRI.QM.WebUI.Areas.Admin.Models.ViewModels.DistributionViewModel
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm("Edit", "Distribution", FormMethod.Post, new { id = "editRoleForm" }))
{
<div class="dialog" id="editRoleDialog">
#Html.TextBoxFor(x => x.name)
#Html.HiddenFor(x => x.ipAddress)
#Html.TextBoxFor(x => x.description)
#Html.HiddenFor(x => x.eyeDee)
#Html.HiddenFor(x => x.destinationPath)
#Html.HiddenFor(x => x.filters)
<div id="permissionsDialogFooter" class="dialogFooter newUser_dialogFooter">
<div class="qm_mediumButton submitButton">save</div>
<div class="qm_mediumButton cancelButton">cancel</div>
<br class="clearfloat" />
</div>
</div>
}
distribution.js
QM.ui.Role = (function ($) {
var _xhrInProgress = false;
function init() {
_bindEvents();
}
// private functions
function _bindEvents() {
var addEditRoleEvents = function (formObj) {
formObj.submit(function () {
var $this = $(this);
if ($this.valid()) {
$.post($this.attr("action"), $this.serialize(), function (response) {
if (response.Success) {
if (response.RedirectUrl) {
window.location.href = response.RedirectUrl;
}
}
});
}
return false;
});
formObj.find(".submitButton").click(function () {
formObj.submit();
});
};
// Edit role dialog
$(".dt-edit a").click(function () {
var $this = $(this);
$.get($this.attr("href"), function (data) {
$(".content").after(data);
QM.ui.Mask.show();
addEditRoleEvents($("#editRoleForm"));
});
return false;
});
}
return {
init: init,
};
})(jQuery);
$(document).ready(QM.ui.Role.init);
in RouteConfig.cs
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "JRI.QM.WebUI.Controllers" }
);
The default model binder of ASP.NET MVC, only work with properties. Your model class doesn't have any property, it does have fields.
To fix that use properties instead field in your model class, like below
public class DistributionViewModel
{
public string name { get; set; }
public string ipAddress { get; set; }
public string description { get; set; }
public Byte eyeDee { get; set; }
public string destinationPath { get; set; }
public List<JRI.DMP.BLL.Filter> filters { get; set; }
}
Also I suggest you to follow the C# code convetions, it says that you should use PascalCase for properties, you can see more details here https://msdn.microsoft.com/en-us/library/ms229043(v=vs.110).aspx
Following the convetion, your class should be like that
public class DistributionViewModel
{
public string Name { get; set; }
public string IpAddress { get; set; }
public string Description { get; set; }
public Byte EyeDee { get; set; }
public string DestinationPath { get; set; }
public List<JRI.DMP.BLL.Filter> Filters { get; set; }
}
I have 2 classes, and try to use the reference in view of a class to another class gives the error:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Class "CLIENTE"
public class Cliente : IEntidadeBase
{
[Key]
[Display(Name = "Cód. de Cliente")]
public int ClienteID { get; set; }
[Display(Name = "Cód. de Pessoa")]
public int PessoaID { get; set; }
public string Matriz { get; set; }
[Display(Name = "Limite de crédito")]
public decimal LimiteCredito { get; set; }
[ForeignKey("PessoaID")]
public virtual Pessoa Pessoa { get; set; }
}
Class "PESSOA"
public class Pessoa : IEntidadeBase
{
[Key]
public int PessoaID { get; set; }
public int? EmpresaIDVinc { get; set; }
[Display(Name = "Matrícula")]
public string Matricula { get; set; }
[Display(Name = "Nome")]
[Obrigatorio]
public string Nome { get; set; }
}
Controller View change:
[Authorize]
[ControleDeAcesso(TipoAcao.Normal)]
public ActionResult Detalhar(int id)
{
using (var db = new ERPContext())
{
Cliente cliente = db.Cliente.Find(id);
var retorno = FlexGestor.Helpers.EntidadeBaseExt.ValidarRegistro(cliente, TipoAcao.Visualizar);
if (retorno != "")
{
TempData["MsgRetornoError"] = retorno;
return RedirectToAction("Index", "Home");
}
return View(cliente);
}
}
View Code:
#model FlexGestor.Models.Cliente
#Html.TituloPagina("Visualizando Cliente")
#using (Html.BeginForm())
{
#Html.ValidationSummary(true);
<div class="linha left">
#Html.HiddenFor(m => m.ClienteID)
#Html.LabelFor(m => m.Pessoa.Nome) #Html.ValidationMessageFor(m => m.Pessoa.Nome)<br />
#Html.TextBoxFor(m => m.Pessoa.Nome, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.LimiteCredito) #Html.ValidationMessageFor(m => m.LimiteCredito)<br />
#Html.TextBoxFor(m => m.LimiteCredito, new { style = "width:250px;" })<br />
#Html.BotaoTelaDetalhar()
</div>
}
<div class="linha rodape"></div>
I'm not 100% sure if this will fix your issue but try changing to this and see if it helps
[Authorize]
[ControleDeAcesso(TipoAcao.Normal)]
public ActionResult Detalhar(int id)
{
Cliente cliente = null;
using (var db = new ERPContext())
{
cliente = db.Cliente.Find(id);
var retorno = FlexGestor.Helpers.EntidadeBaseExt.ValidarRegistro(cliente, TipoAcao.Visualizar);
if (retorno != "")
{
TempData["MsgRetornoError"] = retorno;
return RedirectToAction("Index", "Home");
}
}
if(cliente != null && cliente.pessoa != null)
{
return View(cliente);
}
else
{
// do something else here as the view does not have required stuff
}
}