#html.partial Model Not Found - razor

~/Views/PlanBuilder/PlanBuilder.cshtml
#{
ViewBag.Title = "PlanBuilder";
Layout = "~/Views/Shared/_LayoutPlanBuilder.cshtml";
}
<div id="tabs-1">
<div id="wrap" class="left">
<ul>
#Html.Partial("~/Views/Hall/Index.cshtml");
</ul>
</div>
</div>
~/Views/Hall/Index.cshtml
#model IEnumerable<ShaadiPlanner.Models.Hall>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPlanBuilder.cshtml";
}
#foreach (var item in Model) <!-- ERROR LINE -->
{
<li id="#Html.DisplayFor(modelItem => item.ID)" class="options left">
<div class="box-header">
<h4 class="left"><span class="name">#Html.DisplayFor(modelItem => item.Name)</span> (#Html.DisplayFor(modelItem => item.Area))</h4>
<h4 class="right">Rs. <span class="price">#Html.DisplayFor(modelItem => item.EstCost)</span></h4>
</div>
</li>
}
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Note: When i define Model in the #Html.Partial code like this then #Html.Partial("~/Views/Hall/Index.cshtml", model); it give following error.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0103: The name 'model' does not exist in the current context

Try uppercasing Model, i.e.
#Html.Partial("~/Views/Hall/Index.cshtml", Model);
As #webdeveloper comments, you have not got a model declared in your view!

Related

Property 'name' does not exist on type 'string' ngFor in Angular

I got this error while trying to display an array of objects
Error: src/app/components/timeline/timeline.component.html:9:29 - error TS2339: Property 'name' does not exist on type 'string'.
<h4>{{publication.user.name}}</h4>
~~~~
src/app/components/timeline/timeline.component.ts:10:15
10 templateUrl: './timeline.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component TimelineComponent.
in my timeline.component.html I have this:
<div id="publications">
<div *ngFor = "let publication of publications" class="item-publication">
<div class="panel panel-default">
<div class="panel-body">
<h4>{{publication.user.name}}</h4>
</div>
</div>
</div>
</div>
and this is the getPublications function that I have
getPublications(page){
this._publicationService.getPublications(this.token, page).subscribe(
response => {
console.log(response);
if(response.publications){
this.total = response.total_items;
this.pages = response.pages;
this.publications = response.publications;
if(page > this.pages){
this._router.navigate(['/home']);
}
}else{
this.status= 'error';
}
},
error =>{
var errorMessage = <any>error;
console.log(errorMessage);
if(errorMessage != null){
this.status = 'error';
}
}
);
}
If I make a console.log(response) it shows me the values of the array and the properties are correct (name,surname,email, text etc)
In the HTML code, when I do the loop for the publication's text <h4>{{publication.text}}</h4> it works and even if I use <h4>{{publication.user}}</h4> it shows a list of Objects.
I'm taking an online course and basically copying what the teacher does line by line but IDK why when I try to display name and surname properties, it shows the error that I told you
Thank you for your help.
I found the solution and is related to TS type system so basically I have a model object called publication.ts which includes:
export class Publication{
constructor(
public _id:string,
public text: String,
public file: String,
public created_at: String,
public user: String
){}
}
And the issue was related to the type for the property user so by changing its type to public user: any it worked and now it shows the required fields. Sorry for posting this without a deep search before ask for help. Newbie mistakes
Thanks for the help
You are subscribing to the data so there is a small delay in getting the data. Wrap the tag with a *ngIf to wait for the data to be available.
<div *ngIf="publications" id="publications">
<div *ngFor = "let publication of publications" class="item-publication">
<div class="panel panel-default">
<div class="panel-body">
<h4 *ngIf="publication && publication.user && publication.user.name">{{publication.user.name}}</h4>
</div>
</div>
</div>
</div>

Added a new column to an existing table in SSMS, throwing an error

Tried calling the new column I made in my database via Razor, throwing an error in a different file. I am completely unsure what any of this means.
Server Error in '/' Application.
Invalid column name 'ProductImage'.
Description: An unhandled exception occurred during the execution of the current web request. Please
review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'ProductImage'.
Source Error:
Line 19: {
Line 20: var products = db.Products.Include(p => p.Supplier);
Line 21: return View(products.ToList());
Line 22: }
Line 23:
Here is where I am calling on the item in Razor (my Index view of my controller that I added the new column in)
#foreach (var item in Model)
{
<tr>
<td>
<div class="col-lg-4 col-sm-6">
<div class="single_category_product">
<div class="single_category_img">
<img src="~/Content/img/storefront/#item.ProductImage" alt="">
<div class="category_social_icon">
<ul>
<li><i class="ti-heart"></i></li>
<li><i class="ti-bag"></i></li>
</ul>
</div>
<div class="category_product_text">
<h5>#Html.DisplayFor(x => item.Name)</h5>
<p>#Html.DisplayFor(x => item.Price)</p>
</div>
</div>
</div>
</div>
</td>
<td>
#Html.ActionLink("Details", "Details", new { id = item.ProductID })
#if (User.IsInRole("Admin"))
{
#Html.ActionLink("Edit", "Edit", new { id = item.ProductID })
#Html.ActionLink("Delete", "Delete", new { id = item.ProductID })
}
</td>
</tr>
}

#Html.AntiForgeryToken() throwing null reference error

I'm building the third more or less identical form in an MVC project (meaning I'm copying and pasting to save time). This new form, with only one control is throwing a null reference error on the #Html.AntiForgeryToken() line.
View:
#model SubSheets.ViewModels.TaskItemViewModel
#using (Html.BeginForm("CreateTaskItem", "TaskItems"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => m.Name, "Task Name", new {#class = "control-label col-md-2"})
<div class="col-md-2">
#Html.EditorFor(m => m.Name, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(m => m.Name, "", new {#class = "text-danger"})
</div>
</div>
</div>
}
Controller:
[Authorize]
[HttpPost]
public ActionResult CreateTaskItem(TaskItemViewModel viewModel)
{
/* db context actions */
return View("../WorkItems/CreateWorkItem");
}
The form posts just fine, the data is saved just fine as well. However I get a null reference error, line 13:
Object reference not set to an instance of an object.
Line 11: #using (Html.BeginForm())
Line 12: {
Line 13: #Html.AntiForgeryToken()
Line 14:
Line 15: <div class="form-horizontal">
I thought I understood the Html helper adds a hidden form field that makes sure Post request isn't coming from a third-party domain. I didn't expect to get a null reference exception from a form field?
I had the same thing recently. It wasn't that the model hadn't been initialised and sent to the view; instead, it was due to a ViewData[] item not being initialised, but the error appeared on the #Html.AntiForgeryToken() line which threw me for a while.

Not able to access json Object key

I have a json object as below:
Json
{error: false, message: [,…]}
Inside message:
{convid: "5aeab8a0e5dd7c55942a7ce7", recipient: "Akhil Sindhwani", seen: false, from: "Miti Desai",…}
convid : "5aeab8a0e5dd7c55942a7ce7" from : "Miti Desai" messages :
"asdsad" recipient : "Akhil Sindhwani" seen : false subject : "sasas"
updatedAt : "2018-05-03T07:22:09.367Z"
I am working in Angular and above is the response I get from http service.
Service function:
getUserMessages() {
console.log("getUserMessages");
this._mailingService.getMessages()
.subscribe(conversations => {
this.messageData = conversations
if (conversations) {
console.log( this.messageData);
this.messageData = conversations
}
})
, error => {
console.log("Error");
},
() => {
// THIS IS EXECUTED AFTER THE SUBSCRIBE COMPLETES
console.log( 'this.messageData');
console.log( this.messageData);
}
}
In code above I get a response in conversation which I get that json object.
I put that object in message data.
In html I tried to parse message data as follow:
<div id="messageMenu">
<ul>
<li class='msgBody' *ngFor = "let message of messageData.message">
<div class="msgListingContainer1">
<div class="senderImg">
<img src="../../../../assets/images/profile1.jpg">
</div>
</div>
<div style=" display:inline-block" class="msgListingContainer2">
<span style=" display:inline-block" class="senderName">{{message.recipients}}</span>
<span class="msgTimestamp">5:13pm</span>
<p class="msgheading"><span>Hey alex pretty cool new track you got..</span></p>
</div>
</li>
</ul>
</div>
But I get this error message:
MessageMenuComponent.html:6 ERROR TypeError: Cannot read property
'message' of undefined
I am trying to fetch a key from json and then loop it using ngFor directive it. It is simple, I have done this before.
Can anyone tell me what I am doing wrong?
Any help would be appreciated!
Update
Not sure how it worked.
Didn't change anything in component file.
Changed html to:
<div id="messageMenu">
<ng-container *ngIf="showConversations;else noCnvrstns" >
<ul>
<li class='msgBody' *ngFor = "let message of messageData">
<div class="msgListingContainer1">
<div class="senderImg">
<img src="../../../../assets/images/profile2.jpg">
</div>
</div>
<div style=" display:inline-block" class="msgListingContainer2">
<span style=" display:inline-block" class="senderName">{{message.recipient}}</span>
<span class="msgTimestamp">{{ message.updatedAt | date:'hh:mm a' }}</span>
<p class="msgheading">{{message.messages}}</p>
</div>
</li>
</ul>
</ng-container>
<ng-template #noCnvrstns>
<div class="noConversations">No conversations to show</div>
</ng-template>
</div>
Started getting response.
I didn't understand when messages were in message key of json object then how I able to fetch them out of conversations directly but working for me.
Not adding answer as question itself is ambiguous.
Thanks for help!
Better to use safe navigation ? in case of asnyc calls fetching data. it will not alow angular to throw an error.
Try this -
<li class='msgBody' *ngFor = "let message of messageData?.message">
Also at the time of declaration typecaste messageData: any.
Your JSON file is malformed.
How you can read here:
In JSON, keys must be strings, written with double quotes
Insert double quotes around your keys, this will probably fix the problem.

get an arraylist from a service using HTTP in ANGULAR

i have a component named zoomdetails which contains the specific details of a product
when i click on the product image the zoomdetails component displays and contains the details of the clicked product
so i m using route and adding the id of the product to the URL
the problem is :
when i load the products arraylist from the service and try to get the product by its id and looping the arraylist an error appears and indicates Cannot read property 'length' of undefined
here is the zoomdetails.component.ts code :
(i ve added some log.console comments to see the results)
export class ZoomdetailsComponent implements OnInit {
x: string="";
produitzoom:IProduct;
produits:IProduct[];
errormessage1 :string ;
currentId : number;
constructor(private _route:ActivatedRoute,private _router:Router,private _productServic:ProductdataService)
{
console.log("Logging the route : " + JSON.stringify(_route.snapshot.params));
this.currentId = +_route.snapshot.params['id'];
console.log("Logging the current ID : " + this.currentId)
this._productServic.getProducts()
.subscribe(productss => this.produits=productss ,error=>this.errormessage1= <any>error);
console.log("************************************************************************************")
}
Myspan(){
this._router.navigate(['/']);
}
find (id:number,P:IProduct[]) :IProduct{
console.log("+++++++DANS FIND ERROR +++++++++++++++++++++++++")
for (let product of P )
{
if (product.idpr==id )
{
return product;
}
}
}
ngOnInit() {
console.log("-------------DANS NGONINITTT-------------------------------------------------------------")
this.produitzoom=this.find(this.currentId,this.produits)
console.log(this.produitzoom.productName)
console.log("--------------------------------------------------------------------------")
}
and this is my zoomdetails component .html
<router-outlet></router-outlet>
<div id="zoom" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close" (click)="Myspan()">×</span>
<div class="container">
<div class="row">
<div class="col-md-4 item-photo">
<img src={{produitzoom.imgUrl}} style="width:360px;height:650px;">
</div>
<div class="col-md-6" style="border:0px solid rgba(163, 152, 152, 0.856)">
<span class="pull-right">
<!-- Datos del vendedor y titulo del producto -->
<h1>{{produitzoom.productName}}</h1>
<h4 style="color:#337ab7"> {{produitzoom.author}} <small style="color:#337ab7">(50 ventes)</small></h4>
<!-- Precios -->
<h2 class="title-price"><small>Price</small></h2>
<h3 style="margin-top0px">{{produitzoom.price}} $</h3>
<br> <br>
<!-- Detalles especificos del producto -->
<div class="section" style="background:rgb(222, 228, 222);">
<h5 class="title-attr" >
<div>
<br>
{{produitzoom.description}}
<br> <br>
</div>
</h5>
</div>
<br><br>
<!-- Botones de compra -->
<script>
console.log("Test of value : " + JSON.stringify(produitzoom))
</script>
<button class="btn btn-success right" [routerLink]="['/Authentification',produitzoom]">
<span class="glyphicon glyphicon-shopping-cart"></span> Add to Cart
</button>
</span>
<br> <br> <br> <br>
<ul class="menu-items">
<li class="active">Customers Reviews</li>
</ul>
<div style="width:100%;border-top:1px solid silver">
<p style="padding:15px;">
<small>
Stay connected either on the phone or the Web with the Galaxy S4 I337 from Samsung. With 16 GB of memory and a 4G connection, this phone stores precious photos and video and lets you upload them to a cloud or social network at blinding-fast speed. With a 17-hour operating life from one charge, this phone allows you keep in touch even on the go.
With its built-in photo editor, the Galaxy S4 allows you to edit photos with the touch of a finger, eliminating extraneous background items. Usable with most carriers, this smartphone is the perfect companion for work or entertainment.
</small>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
and these are the errors :
Logging the route : {"id":"1"} zoomdetails.component.ts:22 Logging the current ID : 1 zoomdetails.component.ts:25 ************************************************************************************ zoomdetails.component.ts:50 -------------DANS NGONINITTT------------------------------------------------------------- zoomdetails.component.ts:38 +++++++DANS FIND ERROR +++++++++++++++++++++++++ ZoomdetailsComponent_Host.html:1 ERROR TypeError: Cannot read property 'length' of undefined (from the find method )
ERROR TypeError: Cannot read property 'imgUrl' of undefined (from the html file produitzoom.imgurl)
what should i do !
first, about the imgUrl error, because of the fact that initially produitzoom is undefined, and it gets it's value after an async call, you can change the value of binding to this: [src]="produitzoom? produitzoom.imgUrl : null".
also about the other error, you are calling this.produitzoom=this.find(this.currentId,this.produits) inside your ngOnInit function, but again, bacuase of the fact that the produits is also undefined at the beginning of the component's lifecycle, and gets it's value after an async call. you should move that this.find() call over to the subscribtion's success. something like this:
productss => {
this.produits=productss;
this.produitzoom = this.find(this.currentId,this.produits)
}
Note!!
it's also very important and recommended that if you are subscribing to an observable, you unsubscribe it at the end of that component's Lifecycle (inside ngOnDestroy function). otherwise, this would cause memory leeks and untracable errors... you can do that by defining a property for subscription like:
productsSubscription: Subscription;
dont forget to import Subscription from rxjs/subscription. and then assign the subscription to this property like:
this.productsSubscription = this._productServic.getProducts()
.subscribe(.....);
and inside ngOnDestroy:
ngOnDestroy(){
if(this.productsSubscription){
this.productsSubscription.unsubscribe();
}
}
have that if there to prevent any undefined-related errors.
The problem is that you are loading the products in your constructor, which is asynchronous. Then in your ngOnInit function that is called later on you're using the result of those loaded products, but unfortunately they seem to be not loaded yet. Therefore your P array is not existing yet and so you are using an undefined object in a for loop, which is not working.
ngOnInit() {
console.log("-------------DANS NGONINITTT-------------------------------------------------------------")
// --> here you use the products from the constructor
// but they are not loaded yet, because the loading process takes time and is asynchronous
this.produitzoom=this.find(this.currentId,this.produits)
console.log(this.produitzoom.productName)
console.log("--------------------------------------------------------------------------")
}
What you should do is place the loading of your products in the ngOnInit function as well. There you can wait for the result and then call the find function.
nOnInit(){
// don't subscribe in the constructor, do it in the ngOnInit
this._productServic.getProducts().subscribe(productss => {
// now the results are here and you can use them
this.produits = productss;
// only then you can call the find function safely
this.produitzoom = this.find(this.currentId, this.produits)
}, error => this.errormessage1 = <any>error);
}