Tag Archives: EntityModel

Populate DataGridView with MongoDB Data using Entity in c#

How to populate a DataGridView in Winforms application using C# and data from MongoDB database

Assuming that you already have a model mapped to a collection in MongoDB.

You would like to populate the data in a DataGridView in c#.

We have a model called QuestionBank

 

We will fetch all the records from Mongodb collection using the Filter.Empty

 

 

 

Here is the code

   var documents =  db.QuestionBanks.Find(Builders<QuestionBank>.Filter.Empty).ToListAsync();
   this.dataGridView1.DataSource = documents.Result;

 

 

There is absolutely no need to do any loops to achieve it.

 

 

 

C#- Creating Custom HTML Helpers – Full Example

Custom HTML Helpers can help seperation of code and html and avoid repetion.

What is a HTML Helper ?

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.

Why are HTML Helpers useful ?

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

  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()

 

 

Let us think of a situation.

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.

 

 

Capture

 

 

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.

Capture2

 

 

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

 

 

Better Alternative is to write a Custom HTMLHelper

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

Capture3

The content of the class is as 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>
}

A potentially dangerous Request.Form value was detected from the client – error in MVC4 in vb.net

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

 

How to loop through records in LINQ using VB.NET in Entity Framework

Here is a simple code snippet to loop through the records in VB.NET using LINQ

 

The following code example takes the records from an Entity Framework Model named as Video and then allows to loop through each record.

 

 

Dim List As List(Of Video)

List = (From video In db.Videos Order By video.ID Descending).ToList
For Each item In List
Debug.Print(item.CategoryID)
Debug.Print(item.VideoName)
Next

How to fill a DataGridView using Entity Model in VB.NET

Here is a quick way of filling up and displaying the records from a table in a DataGridView

This post assumes that you already have created a EntityModel in your project

My Entity Model is called SuperHREntities and I have a table called Employees in it

The trick is to you use the .ToArray() after your table name in the following example to display the records.  If you simply try to use db.Employees then the records will not be displayed.

 

Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim db As New SuperHREntities
DataGridView1.DataSource = db.Employees.ToArray()

End Sub

 

 Click on the Image to see it in full screen.

How to fill DataGridViewUsing Entity Model