September 2012 | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 

How to create a hidden field in asp.net MVC 3

Sunday

ASP.NET MVC 3: hidden  field in cshtml:
                                       From your model you can creates from your modela hidden input on the form for the field  that you pass it.

It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.

Consider the following ViewModel class:

public class ViewModeStudent
{
    public string Value { get; set; }
    public int Id { get; set; }
}

Now you want the edit page to store the ID but have it not be seen:

<% using(Html.BeginForm() { %>
    <%= Html.HiddenFor(model.Id) %><br />
    <%= Html.TextBoxFor(model.Value) %>
<% } %>
Which results in the equivalent of the following HTML:
<form name="form1">
    <input type="hidden" name="Id">2</input>
    <input type="text" name="Value" value="Some Text" />
</form>
Please share this post with your friends. If it's useful to you. Thanks!.

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies in asp.net mvc 4

Handling Circular References ASP.NET MVC 4 Json Serialization - asp.net mvc 4
                                     In this post I will explain Circular Reference Serialization Error in MVC Entity frame work. In my latest project I need to get data from database for purpose of Autocomplete.So I need data as JSON format.

When I request the “http://localhost:xxxx/Student/GetStudentJson”

               
My http GetStudentJson Method is bellow
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class StudentController : Controller
    {
        private SchoolDBContext db = new SchoolDBContext();

        public JsonResult GetStudentJson()
        {
      var students = db.Students .Include(s => s.Standard).Include(s => s.StudentAddress);

            return Json(students, JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


My mode class are following
Student.cs
using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class Student
    {
        public Student()
        {
            this.Courses = new List<Course>();
        }

        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public int StandardId { get; set; }
        public virtual Standard Standard { get; set; }
        public virtual StudentAddress StudentAddress { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
    }
}
Standard.cs

using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class Standard
    {
        public Standard()
        {
            this.Students = new List<Student>();
        }

        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }
        public virtual ICollection<Student> Students { get; set; }
    }
StudentAddress.cs

using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class StudentAddress
    {
        public int StudentID { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public virtual Student Student { get; set; }
    }
}
Now I will explain How to solve this problem In this error occur because the student entity class includes Standard and StudentAddress class entity. But In GetStudentJson Method tries to convert only Student class object to Json.So that I got the above error. To solve this error we rewrite the GetStudentJson method

Solution One

public JsonResult GetStudentJson()
   {
            db.Configuration.ProxyCreationEnabled = false;
            var students = db.Students;
            return Json(students, JsonRequestBehavior.AllowGet);
   }
The Out Put is Look like bellow
  [{"StudentID":1,"StudentName":"John","StandardId":1,"Standard":null,
     "StudentAddress":null,"Courses":[]}]


Solution Two
In this type we get selected error

 public JsonResult GetStudentJson()
   {
            var students = from s in db.Students select new { s.StudentID, s.StudentName,s.StandardId };

            return Json(students, JsonRequestBehavior.AllowGet);
   }
Please share this post with your friends. If it's useful to you. Thanks!.

Difference Between Viewresult() and ActionResult() / different ActionResult types - in asp.net mvc 3

Types of ASP.NET MVC 3 Action Results: 
                                         ActionResult is the general base class that all the other results are derived from like ViewResult,JsonResult and so on. ActionResult is an abstract class that can have several subtypes.
Here's a description of different ActionResult types in MVC 3


ViewResult - Renders a specifed view to the response stream

PartialViewResult - Renders a specifed partial view to the response stream

EmptyResult - An empty response is returned

RedirectResult - Performs an HTTP redirection to a specifed URL

RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

JsonResult - Serializes a given ViewData object to JSON format

JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

ContentResult - Writes content to the response stream without requiring a view

FileContentResult - Returns a fle to the client

FileStreamResult - Returns a fle to the client, which is provided by a Stream

FilePathResult - Returns a fle to the client

This way you can return multiple types of results

Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET MVC 4: create dropdownlist from an enum (Enumeration helper)

Thursday

                                                      In one of my previous article I'm explained how to create  a dropdownlist from a controller class. And in this post I'm going to explaine how to create a dropdownlist from an enum.

First create  a helper ennum class with your dropdown items. Here I'm using three options "Daily","Quickly","Weekly".

using System.Reflection;
using System.ComponentModel;
namespace EnumHtmlHelper.Helper
{
    public static class EnumDropDown
    {
        public static string GetEnumDescription<TEnum>(TEnum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.
                   GetCustomAttributes(typeof(DescriptionAttribute), false);
            if ((attributes != null) && (attributes.Length > 0))
                return attributes[0].Description;
            else
                return value.ToString();
        }
        public enum Interval
        {
            [Description("Daily")]
            D = 1,
            [Description("Quick")]
            Q = 2,
            [Description("Weekly")]
            W = 3
        } 
    }    
}

Then add the following code into your (Razor) view to get the dropdown list.

<div class="ddlSmall">
 @{
     var EnumInterval = from Helper.EnumDropDown.Interval n in Enum.GetValues(typeof(Helper.EnumDropDown.Interval))
     elect new SelectListItem
     {
          Value = n.ToString(),
          Text = EnumDropDown.GetEnumDescription(n),
     };
    }
</div>

The output of the above code look like this in page source

<select id="Interval" name="Interval">
         <option value="D">Daily</option>
         <option value="Q">Quick</option>
         <option value="W">Weekly</option>
</select>
The output of the above code look like this in web page


Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET - MVC 4: How to debug asp.net mvc 4 source code / application in VS 2010?

Wednesday

ASP.NET: MVC 4 Debugging applications/Projects in visual studio 2010:

Below the steps for debug your asp.net mvc 4 source code using visual studio 2010 ultimate:


  1. First close all Visual Studio instances. 
  2. Ensure that you are a member of the local debuggers group (Control Panel, Administrative Tools, Local Security Policy, Security Settings, Local Poliies, User Rights Assignment,  Debug Programs).  
  3. Change the following registry key(got start type “regedit” in “Search program and files”  and click regeedit It will open “registry edit” window) HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger\DisableAttachSecurityWarning from 0 to 1. 
  4. Go to IIS Crate a Virtual directory for your web application 
  5. Open the project in VS editor. Right click in the project and click property, it will open the property window 
  6. Click on Web,on Server tag select Use Custom web service and enter virtual path of our web application
  7. Open virtual path in Any one Browser
  8. In VS IDE click Debug tag and click Attached to process and select W3wp.exe and click attach button 
  9. Then put break point(s) and click start  with debugging. 



ASP.NET: MVC 4 Razor View Get Confirm Message Before Delete

ASP.NET MVC 4: Confirmation alert before delete:
This is the sample code for display a confirmation alert message before  delete an employe detail.
                                               
                                     
In View:

@Html.ActionLink("Delete", "DeleteEmp", new { id = item.Id }, new { onclick = " return DeleteConfirm()" })
In Script:

function DeleteConfirm(){
        if (confirm("Are you sure want to delete record"))
            return true;
        else
            return false;     
    }
In Controller:

   public ActionResult DeleteEmp(int id)
   { 
            var empDelete = (from emp in dbml.M_Employees  where emp.Id == id   select emp).Single(); 
            dbml.M_Employees.DeleteOnSubmit(empDelete); 
            dbml.SubmitChanges(); 
            return RedirectToAction("Index"); 
   }

 
 
 

RECENT POSTS

Boost

 
Blogger Widgets