pass the data of GridViewRow of one class to another class - asp.net

I've a class "get_User.cs" inside "UI" folder. I am using GridView to display data of User.
Now I've to pass the data of GridViewRow to another class "ClsUserRecords.cs".
This "ClsUserRecords.cs" is inside folder AppCode -> BusinessObjects -> "ClsUserRecords.cs". how can I do this?
My current code ::
// get_User.cs
private ClsUserRecords.UserRecords SetEmpRecord(GridViewRow selectedRow, string userName)
{
ClsUserRecords.UserRecords obj = new ClsUserRecords.UserRecords();
obj.user_id = CleanText(((HiddenField)selectedRow.FindControl("hidden_user_id")).Value);
obj.user_name = userName;
obj.user_address = CleanText(selectedRow.Cells[12].Text);
return obj;
}
// ClsUserRecords.cs
public class UserRecords
{
public string user_id { get; set; }
public string user_address { get; set; }
public string user_name { get; set; }
}
// do my stuff
Now I want to change the approach. I want to pass the value of GridViewRow without calling the class ClsUserRecords inside get_User. But calling the GridViewRow from the class ClsUserRecords. How can I do this, is it possible or not?

Related

Out-only field in JSON deserialization [duplicate]

We have some configuration files which were generated by serializing C# objects with Json.net.
We'd like to migrate one property of the serialised class away from being a simple enum property into a class property.
One easy way to do this, would be to leave the old enum property on the class, and arrange for Json.net to read this property when we load the config, but not to save it again when we next serialize the object. We'll deal with generating the new class from the old enum separately.
Is there any simple way to mark (e.g. with attributes) a property of a C# object, so that Json.net will ignore it ONLY when serializing, but attend to it when deserializing?
There are actually several fairly simple approaches you can use to achieve the result you want.
Let's assume, for example, that you have your classes currently defined like this:
class Config
{
public Fizz ObsoleteSetting { get; set; }
public Bang ReplacementSetting { get; set; }
}
enum Fizz { Alpha, Beta, Gamma }
class Bang
{
public string Value { get; set; }
}
And you want to do this:
string json = #"{ ""ObsoleteSetting"" : ""Gamma"" }";
// deserialize
Config config = JsonConvert.DeserializeObject<Config>(json);
// migrate
config.ReplacementSetting =
new Bang { Value = config.ObsoleteSetting.ToString() };
// serialize
json = JsonConvert.SerializeObject(config);
Console.WriteLine(json);
To get this:
{"ReplacementSetting":{"Value":"Gamma"}}
Approach 1: Add a ShouldSerialize method
Json.NET has the ability to conditionally serialize properties by looking for corresponding ShouldSerialize methods in the class.
To use this feature, add a boolean ShouldSerializeBlah() method to your class where Blah is replaced with the name of the property that you do not want to serialize. Make the implementation of this method always return false.
class Config
{
public Fizz ObsoleteSetting { get; set; }
public Bang ReplacementSetting { get; set; }
public bool ShouldSerializeObsoleteSetting()
{
return false;
}
}
Note: if you like this approach but you don't want to muddy up the public interface of your class by introducing a ShouldSerialize method, you can use an IContractResolver to do the same thing programmatically. See Conditional Property Serialization in the documentation.
Approach 2: Manipulate the JSON with JObjects
Instead of using JsonConvert.SerializeObject to do the serialization, load the config object into a JObject, then simply remove the unwanted property from the JSON before writing it out. It's just a couple of extra lines of code.
JObject jo = JObject.FromObject(config);
// remove the "ObsoleteSetting" JProperty from its parent
jo["ObsoleteSetting"].Parent.Remove();
json = jo.ToString();
Approach 3: Clever (ab)use of attributes
Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.
Add an alternate, private property setter to the class with the same type as the original property. Make the implementation of that property set the original property.
Apply a [JsonProperty] attribute to the alternate setter, giving it the same JSON name as the original property.
Here is the revised Config class:
class Config
{
[JsonIgnore]
public Fizz ObsoleteSetting { get; set; }
[JsonProperty("ObsoleteSetting")]
private Fizz ObsoleteSettingAlternateSetter
{
// get is intentionally omitted here
set { ObsoleteSetting = value; }
}
public Bang ReplacementSetting { get; set; }
}
For any situation where it's acceptable to have your deserialization-only property be marked internal, there's a remarkably simple solution that doesn't depend on attributes at all. Simply mark the property as internal get, but public set:
public class JsonTest {
public string SomeProperty { internal get; set; }
}
This results in correct deserialization using default settings/resolvers/etc., but the property is stripped from serialized output.
I like sticking with attributes on this one, here is the method I use when needing to deserialize a property but not serialize it or vice versa.
STEP 1 - Create the custom attribute
public class JsonIgnoreSerializationAttribute : Attribute { }
STEP 2 - Create a custom Contract Reslover
class JsonPropertiesResolver : DefaultContractResolver
{
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
//Return properties that do NOT have the JsonIgnoreSerializationAttribute
return objectType.GetProperties()
.Where(pi => !Attribute.IsDefined(pi, typeof(JsonIgnoreSerializationAttribute)))
.ToList<MemberInfo>();
}
}
STEP 3 - Add attribute where serialization is not needed but deserialization is
[JsonIgnoreSerialization]
public string Prop1 { get; set; } //Will be skipped when serialized
[JsonIgnoreSerialization]
public string Prop2 { get; set; } //Also will be skipped when serialized
public string Prop3 { get; set; } //Will not be skipped when serialized
STEP 4 - Use it
var sweet = JsonConvert.SerializeObject(myObj, new JsonSerializerSettings { ContractResolver = new JsonPropertiesResolver() });
Hope this helps! Also it's worth noting that this will also ignore the properties when Deserialization happens, when I am derserializing I just use the converter in the conventional way.
JsonConvert.DeserializeObject<MyType>(myString);
Use setter property:
[JsonProperty(nameof(IgnoreOnSerializing))]
public string IgnoreOnSerializingSetter { set { _ignoreOnSerializing = value; } }
[JsonIgnore]
private string _ignoreOnSerializing;
[JsonIgnore]
public string IgnoreOnSerializing
{
get { return this._ignoreOnSerializing; }
set { this._ignoreOnSerializing = value; }
}
Hope this help.
After i spent a quite long time searching how to flag a class property to be De-Serializable and NOT Serializable i found that there's no such thing to do that at all; so i came up with a solution that combines two different libraries or serialization techniques (System.Runtime.Serialization.Json & Newtonsoft.Json) and it worked for me like the following:
flag all your class and sub-classes as "DataContract".
flag all the properties of your class and sub-classes as "DataMember".
flag all the properties of your class and sub-classes as "JsonProperty" except those you want them not to be serialized.
now flag the properties the you do NOT want it to be serialized as "JsonIgnore".
then Serialize using "Newtonsoft.Json.JsonConvert.SerializeObject" and De-Serialize using "System.Runtime.Serialization.Json.DataContractJsonSerializer".
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace LUM_Win.model
{
[DataContract]
public class User
{
public User() { }
public User(String JSONObject)
{
MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(JSONObject));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(User));
User user = (User)dataContractJsonSerializer.ReadObject(stream);
this.ID = user.ID;
this.Country = user.Country;
this.FirstName = user.FirstName;
this.LastName = user.LastName;
this.Nickname = user.Nickname;
this.PhoneNumber = user.PhoneNumber;
this.DisplayPicture = user.DisplayPicture;
this.IsRegistred = user.IsRegistred;
this.IsConfirmed = user.IsConfirmed;
this.VerificationCode = user.VerificationCode;
this.Meetings = user.Meetings;
}
[DataMember(Name = "_id")]
[JsonProperty(PropertyName = "_id")]
public String ID { get; set; }
[DataMember(Name = "country")]
[JsonProperty(PropertyName = "country")]
public String Country { get; set; }
[DataMember(Name = "firstname")]
[JsonProperty(PropertyName = "firstname")]
public String FirstName { get; set; }
[DataMember(Name = "lastname")]
[JsonProperty(PropertyName = "lastname")]
public String LastName { get; set; }
[DataMember(Name = "nickname")]
[JsonProperty(PropertyName = "nickname")]
public String Nickname { get; set; }
[DataMember(Name = "number")]
[JsonProperty(PropertyName = "number")]
public String PhoneNumber { get; set; }
[DataMember(Name = "thumbnail")]
[JsonProperty(PropertyName = "thumbnail")]
public String DisplayPicture { get; set; }
[DataMember(Name = "registered")]
[JsonProperty(PropertyName = "registered")]
public bool IsRegistred { get; set; }
[DataMember(Name = "confirmed")]
[JsonProperty(PropertyName = "confirmed")]
public bool IsConfirmed { get; set; }
[JsonIgnore]
[DataMember(Name = "verification_code")]
public String VerificationCode { get; set; }
[JsonIgnore]
[DataMember(Name = "meeting_ids")]
public List<Meeting> Meetings { get; set; }
public String toJSONString()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
}
}
}
Hope that helps ...
Depending on where in the application this takes place and if it's just one property, one manual way you can do this is by setting the property value to null and then on the model you can specify that the property be ignored if the value is null:
[JsonProperty(NullValueHandling = NullValue.Ignore)]
public string MyProperty { get; set; }
If you are working on an ASP.NET Core web app, you can globally set this for all properties in all models by setting this in your Startup.cs file:
public void ConfigureServices(IServiceCollection services) {
// other configuration here
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore);
}
with reference to #ThoHo's solution, using the setter is actually all that is needed, with no additional tags.
For me I previously had a single reference Id, that I wanted to load and add to the new collection of reference Ids. By changing the definition of the reference Id to only contain a setter method, which added the value to the new collection. Json can't write the value back if the Property doesn't have a get; method.
// Old property that I want to read from Json, but never write again. No getter.
public Guid RefId { set { RefIds.Add(value); } }
// New property that will be in use from now on. Both setter and getter.
public ICollection<Guid> RefIds { get; set; }
This class is now backwards compatible with the previous version and only saves the RefIds for the new versions.
To build upon Tho Ho's answer, this can also be used for fields.
[JsonProperty(nameof(IgnoreOnSerializing))]
public string IgnoreOnSerializingSetter { set { IgnoreOnSerializing = value; } }
[JsonIgnore]
public string IgnoreOnSerializing;
If you use JsonConvert,IgnoreDataMemberAttribute is ok.My standard library not refrence Newton.Json,and I use [IgnoreDataMember] to control object serialize.
From Newton.net help document.
Is there any simple way to mark (e.g. with attributes) a property of a C# object, so that Json.net will ignore it ONLY when serializing, but attend to it when deserializing?
The easiest way I've found as of this writing is to include this logic in your IContractResolver.
Sample code from above link copied here for posterity:
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
// don't serialize the Manager property if an employee is their own manager
return (Manager != this);
}
}
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(Employee) && property.PropertyName == "Manager")
{
property.ShouldSerialize =
instance =>
{
Employee e = (Employee)instance;
return e.Manager != e;
};
}
return property;
}
}
All of the answers are good but this approach seemed like the cleanest way. I actually implemented this by looking for an attribute on the property for SkipSerialize and SkipDeserialize so you can just mark up any class you control. Great question!
Jraco11's answer is very neat. In case, if you want to use the same IContractResolver both for serialization and deserialization, then you can use the following:
public class JsonPropertiesResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (member.IsDefined(typeof(JsonIgnoreSerializationAttribute)))
{
property.ShouldSerialize = instance => false;
}
return property;
}
}
thats will do the trick, create a property with set only
example 1:
https://dotnetfiddle.net/IxMXcG
[JsonProperty("disabled-protections")]
public JArray DisabledProtections { set => IsPartialResult = (value != null && value.HasValues); }
public bool IsPartialResult { get; private set; }
example 2:
private JArray _disabledProtections;
[JsonProperty("disabled-protections")]
public JArray DisabledProtections { set => _disabledProtections = value; }
public bool IsPartialResult => _disabledProtections != null && _disabledProtections.HasValues;
Use [JsonIgnore] attribute in the public property of the model class.

Passing Values from Page to Another page in List

this is mine model
public class QMSRejection
{
public string Date { get; set; }
public string Grade { get; set; }
public string Resd { get; set; }
public string Remarks { get; set; }
}
this is mine firstpage.xaml.cs from where I am passing a data to another page !
List<QMSRejection> DataToSave = new List<QMSRejection>();
var rej = new QMSRejection();
rej.Date = DateTime.Now.ToShortDateString();
rej.Grade = GradeID;
rej.Resd = ResdId;
DataToSave.Add(rej);
await Navigation.PushAsync(new Rejection2ndForm(DataToSave));
now on the second page I am receiving it, data is coming everything working fine !
public partial class Page2 : ContentPage
{
List<QMSRejection> DataToSave = new List<QMSRejection>();
public Rejection2ndForm(List<QMSRejection> models)
{
InitializeComponent ();
DataToSave = models;
}
}
var rej = new QMSRejection();
rej.Remarks = ent3.Text.ToString();
DataToSave.add(rej);
I have a fields Remarks which I am trying to add to existing data coming from page 1.But these lines are creating another IEnumerable in the datatoSave List and remarks field not getting added to previous data ! What should I do in place of these lines to do ?
As I have to add remarks field through page2.xaml.cs !
this creates a new QMSRejection object and adds it to your list
var rej = new QMSRejection();
rej.Remarks = ent3.Text.ToString();
DataToSave.add(rej);
if you instead want to modify an existing QMSRejection object
// [0] means the first object in the list
DataToSave[0].Remarks = ent3.Text.ToString();

The parameterized query '(#role nvarchar(5),#count int)StudentProcedure #role,#count OUT' expects the parameter '#count', which was not supplied

//Student Controller
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Emial { get; set; }
public string Role { get; set; }
}
//StudentConroller (Here I called Stored Procedure)
public class AccountController : Controller
{
public ApplicationDbClass applicationDbClass;
public AccountController()
{
applicationDbClass = new ApplicationDbClass();
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Student student)
{
var v1 = new SqlParameter();
v1.ParameterName = "#role";
v1.SqlDbType = SqlDbType.NVarChar;
v1.Value = "Admin";
var v2 = new SqlParameter();
v2.ParameterName = "#count";
v2.SqlDbType = SqlDbType.Int;
try
{
var result = applicationDbClass.Students.SqlQuery("StudentProcedure #role,#count OUT", v1, v2).ToArray();
}
catch(Exception e)
{
var m = e.Message;
}
return RedirectToAction("Welcome", "Student");
}
}
//Stored procedure
CREATE OR ALTER PROCEDURE StudentProcedure
#role NVARCHAR(30),
#count INT OUTPUT
AS
BEGIN
SELECT #count=COUNT(dbo.Students.Role)
FROM dbo.Students
WHERE Role=#role;
END
//DbContext Class
public class ApplicationDbClass : DbContext
{
public ApplicationDbClass() : base()
{
Database.SetInitializer<ApplicationDbClass>(new DropCreateDatabaseIfModelChanges<ApplicationDbClass>());
}
public DbSet<Student> Students { get; set; }
public DbSet<LogTable> LogTables { get; set; }
}
// Here I am using code first approch to deal with database using entity framework to call the user created stored procedure. If I make some changes on stored procedure it will not refected directly. Please give me any solution to refects the changes.
You can pass parameters in this way also
SqlConnection cnn = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("StudentProcedure", cnn);
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#role", "Admin");
cmd.Parameters.Add("#count", SqlDbType.Int);
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
string Query = cmd.ExecuteNonQuery().ToString();
Here my goal is to show how to pass normal and output parameter to procedure.
There are two issues here in your code.
You should set the default value for your output parameter. Otherwise C# code will throw an exception if you do not set default value to your output parameter. So your stored procedure should look like this:
ALTER PROCEDURE StudentProcedure
#role NVARCHAR(30),
#count INT = NULL OUTPUT
AS
BEGIN
SELECT #count=COUNT(dbo.Students.Role)
FROM dbo.Students
WHERE Role=#role;
SELECT #count;
END
GO
And the second issue is you've forgot to set Direction of your output parameter:
var sqlParameter_Role = new SqlParameter("#role", "Admin");
var sqlParameter_Count = new SqlParameter();
sqlParameter_Count.ParameterName = "#count";
sqlParameter_Count.SqlDbType = SqlDbType.Int;
sqlParameter_Count.Direction = ParameterDirection.Output;
var result = db.Database
.SqlQuery<ResultForStudentProcedure>("dbo.StudentProcedure #role"
, sqlParameter_Role
, sqlParameter_Count)
.ToList();
public class ResultForStudentProcedure
{
public int Count { get; set; }
}

How to bind bropdown list in Razor View (If view is not bound with any model)

Can anybody suggest me how bind a dropdown list in MVC Razor view. I am using MVC 4. I have a view that is not bound with any model class.
public class Util {
public List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
public class EmployeeType {
public int ID { get; set; }
public string Text { get; set; }
}
I have this sample code. I am new to MVC Now after this I don't know how to bind the collection returned by GetEmployeeTypes() Method to a dropdown list
Your class with method
public class Util {
public List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
Your model class with properties
public class EmployeeType {
public int ID { get; set; }
public string Text { get; set; }
}
This is sample action
public ActionResult ViewName()
{
Util xxx=new Util();
List<SelectList> SelectedItems =new List<SelectList>();
List<EmployeeType> items =xxx.GetEmpTypes();
foreach (var t in items )
{
SelectListItem s = new SelectListItem();
s.Text = t.Text;
s.Value = t.ID;
SelectedItems.Add(s);
}
ViewBag.xxxxx= SelectedItems;
return view();
}
In View
#Html.DropDownList("xxxxx", new SelectList(ViewBag.xxxxx, "Text", "Value"))
This above code just like a key, i don't tested for that code ran successfully. you can get some idea for how to bind dropdown from my code.
I had a Class like this to get all EmployeeTypes
public class Util
{
public List<EmployeeType> GetEmpTypes()
{
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
public class EmployeeType
{
public int ID { get; set; }
public string Text { get; set; }
}
In Controller I have written code to get the List of Employee Types
Util obj = new Util();
var v = obj.GetEmpTypes();
ViewBag.EmployeeTypes = v;
return View();
In the View I have written code to bind dropdown.
#Html.DropDownList("EmployeeTypes",new SelectList(ViewBag.EmployeeTypes,"ID","Text"));
Thanks #Ramesh Rajendran ( Now I understood the concept to bind dropdown)
*strong text*you should create the model selectlist like here:
public static List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
public static SelectList GetMyEmpTypes
{
get { return new SelectList(GetEmpTypes(), "ID", "Text"); }
}
then you access this method in dropdown list like
#Html.DropDownList("Name",yourProjectNameSpace.Util.GetMyEmpTypes())
when you will submit your form then it value bidden with Name get post to controller.
it is not necessary to bind with model class.you can receive the value on controller with the name that you have given in view like:
#Html.DropDownList("Name",yourProjectNameSpace.YourClass.GetEmpTypes())
Now you can recive the name value at controller like:
public ActionResult test(String Name)
{
return view();
}
and make your method static i.e GetEmpTypes() so that you can access it from view.

Simple DropDownList in ASP.NET MVC3 app

I need simple DropDownList in form and I don't want to create something like ViewModel.
I have two models(tables) in relation 1:n:
public class Course
{
public int ID { get; set; }
public string Name { get; set; }
}
and
public class Project
{
public int ID { get; set; }
public int CourseId { get; set; }
public int ProjectNo { get; set; }
public string Name { get; set; }
public DateTime Deadline { get; set; }
}
In the 'Create Project' I want to have DropDownList with Id (as value) and Name(as text) from Course table(model). In the new project will be insert chosen CourseId. How can I do that as simple as possible?
Any particular reason why you don't want to use a ViewModel? They're very helpful for this type of problem.
If you don't want to use a ViewModel, then you can construct a specific class in your controller that is an aggregate of the properties you need from both classes:
public ActionResult Show(int id)
{
Course course = repository.GetCourse(id); // whatever your persistence logic is here
Project project = projectRepository.GetProjectByCourseId(id);
string CourseName = from c in course where
c.ID == project.courseID
select c.Name;
IEnumerable<SelectListItem> selectList =
from c in course
select new SelectListItem
{
Selected = (c.ID == project.CourseId),
Text = c.Name,
Value = project.CourseId.ToString()
};
//add the selectList to your model here.
return View(); //add the model to your view and return it.
}
It would be far easier to have a ViewModel for this, so you could have a strongly typed view. Let me show you:
public class ProjectCourseViewModel
{
public SelectList ProjectCourseList {get; private set; }
public Project Project {get; private set; }
public Course Course {get; private set; }
public ProjectCourseViewModel(Project project, Course course)
{
ProjectCourseList = GetProjectCourseSelectList(project, course)
Project = project;
Course = course;
}
private SelectList GetProjectCourseSelectList(Project project, Course course)
{
IEnumerable<SelectListItem> selectList =
from c in course
select new SelectListItem
{
Selected = (c.ID == project.CourseId),
Text = c.Name,
Value = project.CourseId.ToString()
};
}
}
And then your controller would be really simple:
public ActionResult Show(int id)
{
Course course = repository.GetCourse(id);
Project project = projectRepository.GetProjectByCourseId(id);
ProjectCourseViewModel pcvm = new ProjectCourseViewModel(project, course)
return View(pcvm);
}
And then your view takes in a strongly typed model, and you don't have to rely on ViewData, which is a Good Thing.
Note: I haven't compiled this, just written it. There are probably compilation bugs.
probably you could solve it using the following example:
in your controller include a Viewbag
{
Viewbag.Course = db.course.ToList();
var project = new project.....
}
And in your View use the following pattern:
#Html.DropDownList("CourseId",
new SelectList(ViewBag.Course as System.Collections.IEnumerable,
"CourseId", "Name", Model.ID))
where each field represent:
•The name of the form field (CourseId)
•The list of values for the dropdown, passed as a SelectList
•The Data Value field which should be posted back with the form
•The Data Text field which should be displayed in the dropdown list
•The Selected Value which is used to set the dropdown list value when the form is displayed
more info at: http://www.asp.net/mvc/tutorials/mvc-music-store-part-5
brgds.
In the Controler:
var CourseName = from c in course where
c.ID == project.courseID
select c.Name;
SelectList sl = new SelectList(CourseName);
ViewBag.names= sl;
in the view :
#Html.DropDownList("Name", (SelectList)ViewBag.names)

Resources