Server Side Scripting not working - asp.net

I am new to MVC and creating a sample application by viewing this video.I have created a class in Model and a controller.Now when i try to access Class property through view,i am not able to access it,even when i am writing in view like <%=Model.Id %>,the angular brackets are not yellow marked as in case of server side scripting.I am not able to find where the problem is?
Class Customer in Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcCustomer.Models
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public double Amount { get; set; }
}
}
and Controller is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcCustomer.Models;
namespace MvcCustomer.Controllers
{
public class LoadCustomerAndDisplayController : Controller
{
//
// GET: /LoadCustomerAndDisplay/
public ActionResult Index()
{
Customer customer = new Customer();
customer.Name = "Devesh";
customer.Amount = 22.9;
customer.Id = 1;
return View(customer);
}
}
}
and my strongly typed view(IntelliSense is also not working) is
#model MvcCustomer.Models.Customer
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
The Customer id is: <%= Model.Id %>
</div>
</body>
</html>

First off, you're using a Razor view, not an ASP.NET view, so the syntax is #Model.Id not <%= Model.Id %>.

Your view is coded with Razor.
To initiate server side behavior use #, not <%= ... %>
Have a look here.
http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

Related

debugging the asp.net core web API

I wrote this API in .net. I am trying to call this method through Fiddler and getting the below error message:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/allItProjectsLists/Index</pre>
</body>
</html>
Not sure what am I doing wrong. Is there any way, I can put a breakpoint inside method Index and find out what is wrong. Below is my API code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProjectDetails.Models;
using ProjectDetails.Data;
using ProjectDetails.Interfaces;
namespace ProjectDetails.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AllItProjectsListsController : ControllerBase
{
private readonly KPIContext _context;
private readonly IProject objProject;
public AllItProjectsListsController(IProject _objProject)
{
objProject = _objProject;
}
[HttpGet("/Index")]
public IEnumerable<AllItProjectsList> Index()
{
return objProject.GetAllProjectDetails();
}
[HttpPost]
[Route("api/AllItProjectsLists/Create")]
public int Create([FromBody] AllItProjectsList project)
{
return objProject.AddProject(project);
}
[HttpGet]
[Route("api/AllItProjectsLists/Details/{id}")]
public AllItProjectsList Details(int id)
{
return objProject.GetProjectData(id);
}
[HttpPut]
[Route("api/AllItProjectsLists/Edit")]
public int Edit([FromBody]AllItProjectsList project)
{
return objProject.UpdateProject(project);
}
[HttpDelete]
[Route("api/AllItProjectsLists/Delete/{id}")]
public int Delete(int id)
{
return objProject.DeleteProject(id);
}
[HttpGet]
[Route("api/AllItProjectsLists/GetAppDevList")]
public IEnumerable<AppDev> GetAppDev()
{
return objProject.GetAppDevs();
}
any help with the above debugging will be highly appreciated. In Fiddler, I typed the following URL:
https://localhost:44313/api/AllItProjectsLists/Index
Below is the image from Fiddler:
You need to change [HttpGet("/Index")] to [HttpGet("Index")] on your action for attribute routing.
[HttpGet("/Index")] will be executed for a URL as https://localhost:44313/Index
[HttpGet("Index")] will be executed for a URL as https://localhost:44313/api/AllItProjectsLists/Index
Refer to attribute routing

Display an Icon on a Sitecore page (MVC)

As the question states I just want to display an Icon on my page.
I have a Model Called Driver:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestSitecore.Models
{
public class Driver
{
// Single-Line Text
public HtmlString Heading { get; set; }
// Multi-Line Text
public HtmlString MainContent { get; set; }
// Image
public HtmlString MainImage { get; set; }
// Single-Line Text
public HtmlString Firstname { get; set; }
// Single-Line Text
public HtmlString Surname { get; set; }
// Date
public HtmlString DateOfBirth { get; set; }
// Single-Line Text
public HtmlString Nationality { get; set; }
// Icon
public HtmlString NationalityFlag { get; set; }
}
}
In my model I have defined these fields as HtmlStrings as I want to enable page editor support, but I have added comments above each field to show the Sitecore field type.
I have a controller called DriverController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestSitecore.Repositories;
namespace TestSitecore.Controllers
{
public class DriverController : Controller
{
// GET: Driver
public ActionResult Featured()
{
var repository = new DriverRepository();
var driver = repository.GetDriver();
return View(driver);
}
}
}
The DriverController uses a repository to populate the Models Data and return it to the view.
I have a repository called DriverRepository:
using Sitecore.Mvc.Presentation;
using Sitecore.Web.UI.WebControls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TestSitecore.Models;
namespace TestSitecore.Repositories
{
public class DriverRepository
{
public Driver GetDriver()
{
var driver = new Driver();
var rendering = RenderingContext.Current.Rendering;
var datasource = rendering.Item;
driver.Heading = new HtmlString(FieldRenderer.Render(datasource, Constants.FIELD_HEADING));
driver.MainImage = new HtmlString(FieldRenderer.Render(datasource, Constants.FIELD_MAIN_IMAGE));
driver.Firstname = new HtmlString(FieldRenderer.Render(datasource, Constants.FIELD_FIRSTNAME));
driver.Surname = new HtmlString(FieldRenderer.Render(datasource, Constants.FIELD_SURNAME));
driver.DateOfBirth = new HtmlString(FieldRenderer.Render(datasource, Constants.FIELD_DATE_OF_BIRTH));
driver.Nationality = new HtmlString(FieldRenderer.Render(datasource, Constants.FIELD_NATIONALITY));
driver.NationalityFlag = new HtmlString(FieldRenderer.Render(datasource, Constants.FIELD_NATIONALITY_FLAG));
return driver;
}
}
}
The repository utlises the FieldRenderer.Render method which enables the Page editor support.
And finally I have a view called Featured:
#using TestSitecore.Models
#model Driver
<div class="highlight">
<h2>#Model.Heading</h2>
<div class="row">
#Model.MainImage
</div>
<div class="row">
<div class="col-md-12 col-lg12">
#Constants.FIELD_NAME: #Model.Firstname
<br />
#Constants.FIELD_SURNAME: #Model.Surname
<br />
#Constants.FIELD_DATE_OF_BIRTH: #Model.DateOfBirth
<br />
#Constants.FIELD_NATIONALITY: #Model.Nationality
<br />
#Constants.FIELD_NATIONALITY_FLAG: #Model.NationalityFlag
<br />
</div>
</div>
</div>
When I view the output on my page the Icon field just displays the Sitecore Path to the icon and does not render the image. But it does displays the Main Image field correctly. You can see this from the screen shot below:
I also tried sending back just a plain string rather than HtmlString but that just returns the raw value.
I guess what I'm asking is how do I display my Icon on the page and not the Path in the case of Icons? Or should I just switch the Field type to Image and add the Icons as Images in the media library?
As those flags are not in a Sitecore image field, the renderer will not create the img tag for you. So you have 2 options:
switch the field type to Image and add the flags to Sitecore (as you mentioned)
change the html to display the img tag: <img src="#Model.NationalityFlag"/> (note that you will need to provide a edit posibility for the editors in this case - you could alter the output when in edit mode or use an edit frame)

(are you missing a using directive or an assembly reference?)

i am writing common business logic class in App_code folder for connecting to database using EFW.but showing the following error " Error 1 The type or namespace name 'job' could not be found"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace WebApplication6.App_Code
{
public class BlCommon
{
public List<job> GetJobs()
{
pubs2012Entities pubsobject = new pubs2012Entities();
var x = pubsobject.jobs.ToList<job>();
return x;
}
}
}
and class generated by EFW from jobs table is
namespace WebApplication6.App_Code
{
using System;
using System.Collections.Generic;
public partial class job
{
public short job_id { get; set; }
public string job_desc { get; set; }
public byte min_lvl { get; set; }
public byte max_lvl { get; set; }
}
}
Seem you dont have a reference to assembly wich contain mentioned class
Ok I got it:
Public List<job> GetJobs()
{
pubs2012Entities pubsobject = new pubs2012Entities();
var x = pubsobject.jobs.ToList<job>();
return x;
}
Click on Job, Move the mouse cursor over the blue dash that appear at the bottom of
job click Generate Class and then move your Job.cs code to your new job.cs class and
delete the old one.

how to build a dropdownlistfor in asp mvc4 from a db inside a partial view

while ive build mvc projects i havent done them in asp.net mvc4.5
so pls forgive me if this question seems really obvious to answer
or if im making obvious noob mistakes
pls feel free to correct all issues...
ive actually been googling all weekend and i seem to get bits of answers
but havent been able to pull it all together
so as the title says im trying to build a simple dropdownlistfor
where the data is pulled from the db
to add another layer of complexity
this DDLF is in a partial view
so heres what ive got
model:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace proj.Models
{
public class chartType
{
public int id { get; set; }
[Required]
public string typename { get; set; }
}
public class chartTypeVM
{
[Display(Name = "selectedID")]
public int selectedChartType { get; set; }
public IEnumerable<SelectListItem> List { get; set; }
}
}
controller:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using proj.Models;
namespace proj.Controllers
{
public class HomeController : Controller
{
orojDB db = new orojDB ();
public ActionResult Index()
{
chartTypeVM model = initialiseSM();
return View(model);
}
private chartTypeVM initialiseSM()
{
// make scenario DDL
// using chartTypes for now
var q = db.chartTypes
.Select(ct=> new {
ct.id,
ct.typename
})
.AsEnumerable()
.Select(ct => new SelectListItem {
Value = ct.id.ToString(),
Text = ct.typename
});
var cts = new chartTypeVM{
List = q.AsEnumerable()
};
cts.selectedChartType = 1;
Debug.WriteLine("asdfasdf");
return cts;
}
}
}
view:
#using proj.Models
#model chartTypeVM
<h3>We suggest the following:</h3>
#* *************** sections *************** *#
#section sm {
<div id="sm">
<section class="content-wrapper sm-content">
#Html.Partial("_smPartial", Model)
</section>
<div class="smCloseD"><img src="/Images/closeArrow.png" alt="Open Scenario Manager" /></div>
<div class="clear"></div>
</div>
}
main layout (most of it not shown) :
#using proj.Models
#model chartTypeVM
<section class="content-wrapper main-content">
#RenderBody()
</section>
#RenderSection("sm",false);
and finally the partial:
#using proj.Models
#model chartTypeVM
<section class="smVars">
<div class="varLabel">Scenario:</div>
<div class="varInput">#Html.DropDownListFor( model=>model.selectedChartType, (SelectList)model.List)</div>
</section>
with the things ive tried
i getting errs like:
- The name 'model' does not exist in the current context
- or the one about not being able to use dynamic variables
- or something being inferred
anyways if you could help id be very grateful
=:-)
thanks!
In order to use DropDownListFor helper your view needs to be strongly typed to a model. In your case that would be the chartTypeVM class. So add a #model directive to the top of your partial view indicating the view model being used:
#model chartTypeVM
<section class="smVars">
<div class="varLabel">Scenario:</div>
<div class="varInput">
#Html.DropDownListFor(model => model.selectedChartType, (SelectList)Model.List)
</div>
</section>

Partialview and passing data to layout MVC3

i want to show categories to all pages by using layout and here my way:
here my model (NewsCategoriesModel)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace GiaoXuKeSat.Models
{
public class NewsCategoriesModel
{
public int NewsCategoriesID { get; set; }
public string NewsCategoriesName { get; set; }
}
}
Here Partialview (_NewsCategories)
#using System.Linq;
#using System.Linq;
#model IEnumerable<GiaoXuKeSat.Models.dms_NewsCategory>
#foreach (var item in Model) {
<ul id="dmsMenuULUL">
<li>#item.NewsCategoriesName</li>
</ul>
}
and i print that partialview to layout
#Html.Partial("_NewsCategories");
but i got Object reference not set to an instance of an object.
at
#foreach (var item in Model) {
You need to pass the model that your partial view needs to it. Such as.
#Html.Partial("_NewsCategories", Model.NewsItems);
If you leave the model out, you are simply passing the current view model to your partial. You can also use the ViewBag.
If you are calling a Partial from the master/layout page it is unlikely you'll have your model available on every single page. So in this case, it is better to create a controller/action that returns your news item model to a partial view and then call with...
#Html.Action("NewsCategories", "NewsController");
Which will then run the specified action and display the partial view that the action calls.

Resources