Display an Icon on a Sitecore page (MVC) - icons

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)

Related

(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>

Server Side Scripting not working

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

ASP.NET Cannot initiate instance object of a Class I created

So I created a class file Persons to my website project and placed this in a folder called App_Code.
But now in my default.aspx.cs I cannot seem to create i.e. Persons test = new Persons();
Says
Type or Namespace Persons not found
This is my persons class so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.App_Code
{
public class Persons
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string DisplayFullName()
{
string info;
info = "FullName is: " + FirstName + " " + LastName;
return info;
}
public void setData(String sLine)
{
this.FirstName = "Test";
}
}
}
You need to import the appropriate Namespace in your Code behind(default.aspx.cs):
using WebApplication1.App_Code;
Your Person page and your aspx code page are in different namespaces. You cannot resolve type names across namespaces without importing them with the uses keyword.
Add
using WebApplication1.App_Code;
To the top of your default.aspx code behind page.
If you mouse over Person where it has the error, you should get a little helper popup that has the option of adding the missing using clause automatically!
If your working purely with an aspx file with no code behind, use:
<%# Import namespace="MyProgram.MyNamespace" %>
So in your case:
<%# Import namespace="WebApplication1.App_Code" %>

How to pass complex type using json to ASP.NET MVC controller

I have a View that allows a user to enter/edit data for a new Widget. I'd like to form up that data into a json object and send it to my controller via AJAX so I can do the validation on the server without a postback.
I've got it all working, except I can't figure out how to pass the data so my controller method can accept a complex Widget type instead of individual parameters for each property.
So, if this is my object:
public class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
I'd like my controller method to look something like this:
public JsonResult Save(Widget widget)
{
...
}
Currently, my jQuery looks like this:
var formData = $("#Form1").serializeArray();
$.post("/Widget/Save",
formData,
function(result){}, "json");
My form (Form1) has an input field for each property on the Widget (Id, Name, Price). This works great, but it ultimately passes each property of the Widget as a separate parameter to my controller method.
Is there a way I could "intercept" the data, maybe using an ActionFilterAttribute, and deserialize it to a Widget object before my controller method gets called?
Thanks Jeff, that got me on the right path. The DefaultModelBinder is smart enough to do all the magic for me...my problem was in my Widget type. In my haste, my type was defined as:
public class Widget
{
public int Id;
public string Name;
public decimal Price;
}
Notice that the type has public fields instead of public properties. Once I changed those to properties, it worked. Here's the final source code that works correctly:
Widget.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Widget.aspx.cs" Inherits="MvcAjaxApp2.Views.Home.Widget" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
function SaveWidget()
{
var formData = $("#Form1").serializeArray();
$.post("/Home/SaveWidget",
formData,
function(data){
alert(data.Result);
}, "json");
}
</script>
<form id="Form1">
<input type="hidden" name="widget.Id" value="1" />
<input type="text" name="widget.Name" value="my widget" />
<input type="text" name="widget.Price" value="5.43" />
<input type="button" value="Save" onclick="SaveWidget()" />
</form>
</asp:Content>
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace MvcAjaxApp2.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
ViewData["Title"] = "About Page";
return View();
}
public ActionResult Widget()
{
ViewData["Title"] = "Widget";
return View();
}
public JsonResult SaveWidget(Widget widget)
{
// Save the Widget
return Json(new { Result = String.Format("Saved widget: '{0}' for ${1}", widget.Name, widget.Price) });
}
}
public class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Note that (in MrDustpan's solution) the parameter name widget in the MVC Action method must match with the prefix used in the name attribute in the ASPX file.
If this is not the case then the Action method will always receive a null object.
<input type="text" name="widget.Text" value="Hello" /> - OK
<input type="text" name="mywidget.Text" value="Hello" /> - FAILS
Phil Haack has a good blog post about model binding that might be helpful. Not 100% what you're talking about here, but I think it might give you a better overall understand about the DefaultModelBinder.
What you want to do is structure your javascript form object in the same way your backend object is structured:
{ Id : "id", Name : "name", Price : 1.0 }
Then use the toJSON plugin to convert it into the above string. You send this string to your backend and use something like the JayRock libraries to convert it to a new Widget object.

Resources