Add the name space in your controller at the top
using Microsoft.AspNet.Identity;
Wherever you need to get the user id use the following code in your controller
string userId = User.Identity.GetUserId();
Add the name space in your controller at the top
using Microsoft.AspNet.Identity;
Wherever you need to get the user id use the following code in your controller
string userId = User.Identity.GetUserId();
Scenario
I had a Visual Studio 2013 project using MVC4. The application was working fine in my local machine. But when I deployed the application using FileSystem( in this method all the files for the project gets copied to a folder on your local machine, then you can copy all these files to your webhost and your application should start working.)
I got the following error when I deployed the application using this method.
How to Fix it?
I searched on the web for some time to get the answer and in the end I discovered that the System.Web.HTTP.WebHost.DLL file was not being copied to my published folder and hence the error.
1. Go to the solution Explorer in Visual Studio
2. Go to the References
3. Right Mouse Click on the System.Web.HTTP.WebHost entry to check its prooperties and I found that COPY LOCAL proeprty was set to false and hence the file was not being copied to my published folder.
4. I changed the COPY LOCAL to true and then the file gets copied to my published folder and gets deployed correctly.
It is just a method that will return a string which can contain any content you wan from a simple string to a table of data.
method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>
and <img>
tags. In ASP.NET we have many standard HTML Helpers
In a web page we need to list the features of a product.
If the feature is present then show a Tick
If the feature is missing then show a Cross
As shown below.
This is achieved by using two different CSS classes which will render the Tick or the Cross
When I use my CSS class “plain” it will render a Cross
When I use the class “checked” it shows a Tick.
Now in razor view you would typically use the
@Html.DisplayFor(model => model.Alarm) which would render a standard check box ( if true then the checkbox will be ticked and if false the checkbox will be empty) But we want a better display hence we want to make use of our CSS classes.
In order to show the customised CSS we will have to write some logic in the Razor view which is not preferred at all as we would like to keep the logic out from the views and secondly it will need a lot of code as for each item we will have to use some kind of If loop as shown below.
Not recommended
@if (Model.AirConditioning == true)
{
<li class=”ticked”>@Html.LabelFor(model => model.AirConditioning)</li> }
else
{
<li class=”plain”>@Html.LabelFor(model => model.AirConditioning)</li> }
Let us write a Custom HTML Helper for it.
Create a Class
I created a folder called HTMLHelpers in my project and then created a class called myHTMLHelpers.cs as shown below
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace myapplication.Helpers { public static class myHTMLHelpers { public static IHtmlString TickOrCross(bool content) { string htmlString = ""; if(content==true) { htmlString = String.Format("checked"); // if content is true then we want the CSS class checked } else { htmlString = String.Format("plain"); // if content is falsethen we want the CSS class plain } return new HtmlString(htmlString); } } }
How te make use of this HTML Helper ?
Go to your Razor View
at the top of the page add the namespace under which we created our helper class
@using myapplication.Helpers
at the right place in your razor view I have made use of our custom html helper.
We pass the model value to it and it will set the class name accordingly to display a Tick or a Cross
<ul class=”span2″>
<li class=”@myHTMLHelpers.TickOrCross(Model.AirConditioning)“>Air Conditioning</li>
<li class=”@myHTMLHelpers.TickOrCross(Model.Alarm)“>Alarm</li>
</ul>
The other way would have been to put the logic into the view using the if block in our code,. which is not a good practice.
@if (Model.AirConditioning == true)
{
<li class=”ticked”>Air Conditioning</li> }
else
{
<li class=”plain”>Air Conditioning</li>
}
If you want to password protect some pages on your MVC4 site using the Forms Authentication then it is best to to protect the whole site and then selectively allow Anonymous Access to the pages which are to be shown to every visitor.
Open the FilterConfig.VB file and add the line
filters.Add(New AuthorizeAttribute) in it
Once you run your application you would see that all the pages of your website are now protected, the users have to register before they can access.
Imports System.Web Imports System.Web.Mvc
Public Class FilterConfig
Public Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection)
filters.Add(New HandleErrorAttribute())
filters.Add(New AuthorizeAttribute)
End Sub
End Class
If you need to allow some pages for anonymous view then add the following decoration.
<AllowAnonymouse()> on each page which you want to open up for anonymous access.
<AllowAnonymous()>
Function Index() As ActionResult
ViewData("Message") = "Modify this template to jump-start your ASP.NET MVC application."
Dim rep As New RepositoryRealEstate
ViewBag.AgentCount = rep.GetAgentsCount
ViewBag.ProperyCount = rep.GetPropertyCount
ViewBag.VendorCount = rep.getvendorcount
Return View()
End Function
If you are trying to use the simplemembership in mvc4 in visual studio and if you get this error
Here is a simple fix for this
This error will come when your table owner is not dbo.
Change the table ownership in SQL Server by using the following command
EXEC sp_changeobjectowner 'UserProfile', 'dbo'
There are numerous example for C3 but I had to spend quite some time to adapt it to my project using VB.NET
Hope it can be of help to you.
I assume that you have
already added the GridMVC package from NUGET.
Here are step by step guide
Controller
No change needed , see a sample below,
Function Index() As ActionResult
Return View(db.Categories.ToList())
End Function
View
Add the following import at the top of your view
@imports GridMVC.html
You would need to reference the following also
Add the stylesheets (check the location after you install the GridMVC package)
<link href=”~/Content/Gridmvc.css” rel=”stylesheet” />
<link href=”~/Content/gridmvc.datepicker.min.css” rel=”stylesheet” />
For your paging support
Install the PagedList package also
Once you have installed this package then add the following reference to your view, this will help you format your paging buttons
properly.
<link href=”~/Content/PagedList.css” rel=”stylesheet” />
Add the following code for your Grid to appear – In the following examples my Model has three fields – CatId, CatName
and ParentCatId. Make changes to suit your needs.
@Html.Grid(Model).Columns(Function(columns)
columns.Add(Function(o) o.CatID).Titled(“Cat #“).SetWidth(40)
columns.Add(Function(o) o.CatName).Titled(“Category“).SetWidth(100)
columns.Add(Function(o) o.ParentCatID).Titled(“Parent Cat #“).SetWidth(40)
End Function
).WithPaging(10).Sortable(True)
In your Create Actions in a Controller in MVC4, if you try to save text with html tags then you get this annoying error.
A potentially dangerous Request.Form value was detected from the client
Description: ASP.NET has detected data in the request that is potentially dangerous because it might include HTML markup or script. The data might represent an attempt to compromise the security of your application, such as a cross-site scripting attack. If this type of input is appropriate in your application, you can include code in a web page to explicitly allow it. For more information, see http://go.microsoft.com/fwlink/?LinkID=212874.
This is a great protection if you do not want your client to save html text.
Here is how to get rid of this error
In the following example we have a create action which saves a new record. MVC4 controller will have two functions.
The first function is for GET ( this is the one which will render the page to save the new record
The second function is for POST. This function is responsible to receive the model
which has been populated by the data which the user has filled in on the form. We have to add the following text
<ValidateInput(False)>
for C# add
[ValidateInput(false)]
‘ GET: /admin/ManageAds/Create
Function Create() As ActionResult
Return View()
End Function
‘ POST: /admin/ManageAds/Create
<HttpPost()> _
<ValidateAntiForgeryToken()> _
<ValidateInput(False)>
Function Create(ByVal ad As Ad) As ActionResult
If ModelState.IsValid Then
db.Ads.Add(ad)
db.SaveChanges()
Return RedirectToAction(“Index”)
End If
Return View(ad)
End Function
Here is a simple function to generate the RSS feeds.
This article assumes that you are using MVC4 project with Entity Framework. Just iterate through
the relevant table to pick your data which you want to show in the RSS feed.
Remember to add the following import statements at the top of your controller
Imports System.Xml
Imports System.IO
In your controller create a function as shown below. There is no need to create a corresponding View for it
as the function will write to the RESPONSE and the XML output will be provided by the XMLTextWriter.
Function RSSNewArticles() As Action
Response.Clear()
Response.ContentType = “text/xml”
Dim objX As New XmlTextWriter(Response.OutputStream, Encoding.UTF8)
objX.WriteStartDocument()
objX.WriteStartElement(“rss”)
objX.WriteAttributeString(“version”, “2.0”)
objX.WriteStartElement(“channel”)
objX.WriteElementString(“title”, “MyWebsite.com RSS Feed“)
objX.WriteElementString(“link”, “http://mywebsite.com“)
objX.WriteElementString(“description”, “My website New Articles Feed“)
‘ objX.WriteElementString(“copyright”, “(c) 2014, best-answer.net“)
objX.WriteElementString(“ttl”, “10”)‘Populate record for the RSS feed
For Each item In db.MyDataTable
objX.WriteStartElement(“item”)
objX.WriteElementString(“title”, item.CatName)
objX.WriteElementString(“link”, “http://mywebsite/” & item.RecordID & “/” & item.TitleName)
objX.WriteElementString(“pubDate”, Now)
objX.WriteEndElement()
NextobjX.WriteEndElement()
objX.WriteEndElement()
objX.WriteEndDocument()
objX.Flush()
objX.Close()
Response.End()
End Function
In SQL you would use the following query to get the count of number of rows in a table.
Select count(*) from tblMyData
In LINQ
In VB.NET you would use the following to get it
Dim v = (From u In MyContext.MyTable).Count()
In C# you would use the following syntax
var v= (from u in MyContext.MyTable).Count();
You variable v will not contain the count
If you have had experience this problem then read ahead it is a simple fix.
Here are the step to reproduce this problem in Visual Studio
Here is what happened, I had a MVC4 project which was working fine. I created a new area called Admin.
Created a new controller and a view in the admin area. But when calling this view, it would give 404 error.
Tried few things and did some research on the net as usual.
Here is the simple fix which seems to work.
Go to your controller and add the namespace at the top . Just after the imports. Note that admin is the name of my area.
Change it according to your area name
Step 1
Imports System.Data.Entity
Namespace Areas.admin
You controller code is here
End Namespace
Step 2
Go to your Area and look for a file called
adminAreaRegistration.vb ( again admin is my area name, if your area is called sales then you should have a file called sales
AreaRegistration.vb. And your namespace will be Areas.sales.)Ensure that the name space which you have in your controller and the adminAreaRegistrarion.vb is the same
Namespace Areas.admin
Public Class adminAreaRegistration
Inherits AreaRegistrationPublic Overrides ReadOnly Property AreaName() As String
Get
Return “admin”
End Get
End PropertyPublic Overrides Sub RegisterArea(ByVal context As System.Web.Mvc.AreaRegistrationContext)
context.MapRoute( _
“admin_default”, _
“admin/{controller}/{action}/{id}”, _
New With {.action = “Index”, .id = UrlParameter.Optional} _
)
End Sub
End Class
End Namespace