I have two tables (NPG_Chemical and NPG_Chemical_Synonym):
public partial class NPG_Chemical
{
[Key]
[Column(TypeName = "numeric")]
public decimal NPG_Chemical_ID { get; set; }
[StringLength(256)]
public string Chemical { get; set; }
}
public partial class NPG_Chemical_Synonym
{
[Key]
[Column(TypeName = "numeric")]
public decimal NPG_Chemical_Synonym_ID { get; set; }
[ForeignKey("NPG_Chemical_ID")]
[Column(TypeName = "numeric")]
public decimal NPG_Chemical_ID { get; set; }
[StringLength(512)]
public string Synonym { get; set; }
}
In the NPG_ChemicalController I have something like:
[HttpPost]
public ActionResult Create(NPG_ChemicalViewModel model)
{
using (var context = new NPG_Model())
{
var chemical = new NPG_Chemical();
chemical.Chemical = model.NPG_Chemical.Chemical;
context.NPG_Chemical.Add(chemical);
var synonym = new NPG_Chemical_Synonym();
synonym.Synonym = model.NPG_Chemical_Synonym.Synonym;
synonym.NPG_Chemical_ID = chemical.NPG_Chemical_ID;
context.NPG_Chemical_Synonym.Add(synonym);
context.SaveChanges();
}
return View();
}
and NPG_ChemicalViewModel:
namespace NPG_Administrative_Utility.Models
{
public class NPG_ChemicalViewModel
{
public NPG_ChemicalViewModel()
{
NPG_Chemical = new NPG_Chemical();
NPG_Chemical_Synonym = new NPG_Chemical_Synonym();
}
public NPG_Chemical NPG_Chemical { get; set; }
public NPG_Chemical_Synonym NPG_Chemical_Synonym { get; set; }
}
}
When I try to create a view based on NPG_ChemicalViewModel, it shows:
Can any one help me on this?
You'll need a view model. At the simplest, you can just do something like:
public class NPG_ChemicalViewModel
{
public NPG_ChemicalViewModel()
{
NPG_Chemical = new NPG_Chemical();
NPG_Chemical_Synonym = new NPG_Chemical_Synonym();
}
public NPG_Chemical NPG_Chemical { get; set; }
public NPG_Chemical_Synonym NPG_Chemical_Synonym { get; set; }
}
Then, change your action to accept this:
public ActionResult Create(NPG_ChemicalViewModel model)
In your view, you would generate the individual properties like:
#Html.EditorFor(m => m.NPG_Chemical.Chemical)
However, it's far better to only include the properties on your view model that you want to be edited:
public class ChemicalViewModel
{
public string Chemical { get; set; }
public string Synonym { get; set; }
}
Then, in your action, you just map this posted data where it should go:
var chemical = new NPG_Chemical();
chemical.Chemical = model.Chemical;
context.NPG_Chemical.Add(chemical);
var synonym = new NPG_Chemical_Synonym();
synonym.Synonym = model.Synonym;
synonym.NPG_Chemical_ID = chemical.NPG_Chemical_ID;
context.NPG_Chemical_Synonym.Add(synonym);
That said, there's some significant issues with your code here. First, it looks like you're dealing with a one-to-one or one-to-many relationship here between Chemical and Synonym, but right now, you have no foreign keys being utilized. You should add a navigation property to your synonym class:
[ForeignKey("NPG_Chemical_ID")]
public NPG_Chemical Chemical { get; set; }
That tells Entity Framework that you have a relationship and among other things allows it to automatically fill in IDs as necessary. For example, with that, you could now simply do:
synonym.Chemical = chemical;
Instead of directly referencing the ID. That way, if the id is autogenerated or otherwise unknown before saving, the relationship will still be preserved. Whereas, without it, you'd have to save chemical first, set the autogenerated id on synonym and then save the synonym in a separate transaction.
Second, if you're going to use keys typed as "numeric". Then, you're going to be responsible for generating a unique numeric string for each record. That's a huge pain, as it's going to require checking a proposed id against other existing record ids before actually saving. Otherwise, you run the risk of a primary key collision. It's far better to use a standard autoincrementing PK or barring that, at least a GUID, where you're assured a reasonably low risk of collisions occurring.
Third, you should absolute not use using with your context. Here it's not a big deal, since, you're only saving and not reading data from the database, but in a typical view, lazy-loading will kick you in the posterior quick doing that. Your context should be request-scoped, either as an instance variable on your controller (since the controller is newed up and disposed with each request) or using dependency injection. You never want to create an instance of your context anywhere else, including an action method.
Related
Problem: I have a Mongo document that includes two arrays. One of the arrays is large, with subdocuments. This one serializes with no problem. Another is a simple array of this type:
staffgroups {"Tech","Sales"}
This one will not serialize. I get errors saying it's a BsonArray. The closest I've been able to get to serializing it produces a string. I need a JSON object.
Code time:
public class specialtyGroup
{
public ObjectId _id { get; set; }
public string name { get; set; }
public string location { get; set; }
public coachConfig config { get; set; }
public schedules[] coaches { get; set; }
public BsonArray staffgroups { get; set; }
}
And the webservice:
public void GetGroups()
{
var client = new MongoClient();
var db = client.GetDatabase("MongoTul");
var coll = db.GetCollection<specialtyGroup>("specialtyGroups");
string cname = HttpContext.Current.Request.Params["loc"];
var creatures = coll.Find(b => b.location == cname)
.ToListAsync()
.Result;
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(creatures));
}
I've tried using aggregation and projecting. I've tried creating an additional class for staffgroups (which works for my complex array). And a few other things. All no good.
Most common error looks like this: Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonBoolean'.
I spent hours on this before posting here, then after posting I figured it out in 30 mins. Sorry.
The answer is staffgroups should be "public string[] staffgroups {get; set;}
So if any other rubes like me have that question, there's the answer.
I have created an application for several stores to fill in a questionnaire, the application has several tables within the database. Two of them are the ones I am focusing on which are Audit and Storequestions. The Audit table contains the data for the stores for example: storename, and its primary key is “AuditId”. The storesquestion table contains all the questionnaire table and AuditId as a foreign key form the Audit table.
I am wanting to create a Read Only tick box as an indication in order to find out which stores has completed the questionnaire as the only way I know which has completed the questionnaire is by looking in the database. My approach to re4solve this matter was to create a new column called read only within the Audit table with a Boolean datatype so when a store has completed the questionnaire it will set the read only row to 1(true).
Could do with a bit of Help as I don’t seem to go forward at the moment
Thanks in advance
public ActionResult Create()
{
StoreQuestions sq = new StoreQuestions();
sq.AuditId = (int)System.Web.HttpContext.Current.Session["AuditId"];
return View(sq);
}
//
// POST: /StoreQuestions/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreQuestions storequestions)
{
if (ModelState.IsValid)
{
db.StoreQuestions.Add(storequestions);
db.SaveChanges();
return RedirectToAction("Details", "Audit", new { id = storequestions.AuditId });
}
return View(storequestions);
}
ViewModel
public class MainModel
{
public StoreAudit StoreAudit { get; set; }
public StoreQuestions StoreQuestion { get; set; }
public List<StoreAudit> StoreAuditList { get; set; }
public List<StoreQuestions> StoreQuestionsList { get; set; }
public List<User> User { get; set; }
public List<string> StoreWindow { get; set; }
}
}
Okay I think I understand what you're trying to do. In order to update the readonly property to true you have to find the audit record and then change the value of that record's readonly property.
Like so:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreQuestions storequestions)
{
if (ModelState.IsValid)
{
Audit findingAudit = db.AuditTable.Find(storequestions.AuditId);
// db being your connectionstring property
findingAudit.readonly = true;
db.StoreQuestions.Add(storequestions);
db.SaveChanges();
return RedirectToAction("Details", "Audit", new { id = storequestions.AuditId });
}
return View(storequestions);
}
I hope this helps!
First of all, this is not exactly a duplication of the dozens of other posts and I have tried all of them and none of them work.
I have a model that contains many more values than my web api consumers need.
public class Publication
{
[Key]
public int PublicationID { get; set; }
public string PublicationTitle { get; set; }
public string Frequency { get; set; }
public DateTime NextIssueDate { get; set; }
public DateTime SpaceDeadline { get; set; }
public DateTime MaterialsDeadline { get; set; }
public DateTime CreatedDt { get; set; }
public string CreatedBy { get; set; }
public DateTime UpdatedDt { get; set; }
public string UpdatedBy { get; set; }
}
I only want say a few of the fields to be passed in the API. I've tried this code but instead of leaving out say UpdateBy in the Json result, it returns it with a null value. How do I get rid of that? I've tried several dozen variations but they either fail to compile or fail to return results.
public IQueryable<Publication> GetPublications()
{
return db.Publications
.ToList()
.Select(p => new Publication {
PublicationID = p.PublicationID,
PublicationTitle = p.PublicationTitle,
Frequency = p.Frequency,
NextIssueDate = p.NextIssueDate
})
.AsQueryable();
}
Don't serialize your DAO. Create a complete contract and then serialize it selectively. To creating different contracts for different cases, you could simplify it using Json.Net; you could just create a custom contract resolver and use it as a parameter of SerializeObject() like so
static void Main(string[] args)
{
var person = new TestContract {FirstName = "John", LastName = "Doe", Age = 36};
var firstNameContract = new SelectiveSerializer("firstname");
var allPropertiesContract = new SelectiveSerializer("firstname, lastname, age");
var allJson = JsonConvert.SerializeObject(
person,
Formatting.Indented,
new JsonSerializerSettings {ContractResolver = allPropertiesContract});
var firstNameJson = JsonConvert.SerializeObject(
person,
Formatting.Indented,
new JsonSerializerSettings {ContractResolver = firstNameContract});
Console.WriteLine(allJson);
// {
// "FirstName": "John",
// "LastName": "Doe",
// "Age": 36
// }
Console.WriteLine(firstNameJson);
// {
// "FirstName": "John",
// }
}
public class SelectiveSerializer : DefaultContractResolver
{
private readonly string[] _fields;
public SelectiveSerializer(string fields)
{
var fieldColl = fields.Split(',');
_fields = fieldColl
.Select(f => f.ToLower().Trim())
.ToArray();
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = o => _fields.Contains(member.Name.ToLower());
return property;
}
}
public class TestContract
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Without much effort, you could probably work this into your default mediatype formatter (in the pipeline) to look for a parameter in the request called 'fields' or whatever and then use the custom contract resolver if present, and then it would be seamless default behavior to limit fields if specified or serialize the entire object if not specified.
On the academic side, here is the justification:
Any modification to the data is considered a "view concern" which means, in an API, it should controlled by query parameters and accept header. In this case, the "representation" of the data is application/json and you've chose to "filter" the returned fields. All of this can (and should be, imo) be handled during serialization. So your "model" in this case will always be the full model vs. some subset of the model. The full model in this example contains first name, last name, and age. In reality, this could be hundreds of properties. If you want to allow the client to choose a subset of the complete model, this is how you could do it with selective serialization.
You can similar behaviors in graph apis. There, the default for large models is that you get an empty object if you don't specify fields, forcing the client to be very specific about what it asks for, which is great when payload size matters (e.g. mobile applications). And, there's nothing stopping from creating field presets like 'name' which could mean 'firstname, lastname' or 'all' which includes all properties.
I've never been a fan of having hundreds of data objects that all serve some ad hoc requirement for a data set that is used in 20 different contexts where some cases require more data while others require less. IMO if you have to go through the same process to get the data, whether it complete or not, you shouldn't waste your time creating additional objects to frame the data for the sake of the client, and this should help you achieve that.
It's because you're returning a collection of Publication objects so you will get every property that is contained in that class, whether you populate it or not. If you want to return a subset of the properties then create a class that has only the properties you want to return and create an instance of that class in your query.
public IQueryable<WhatIReallyWantToReturn> GetPublications()
{
return db.Publications
.ToList()
.Select(p => new WhatIReallyWantToReturn {
PublicationID = p.PublicationID,
PublicationTitle = p.PublicationTitle,
Frequency = p.Frequency,
NextIssueDate = p.NextIssueDate
})
.AsQueryable();
}
private class WhatIReallyWantToReturn
{
public int PublicationID { get; set; }
public string PublicationTitle { get; set; }
public string Frequency { get; set; }
public DateTime NextIssueDate { get; set; }
}
using Newtonsoft.Json;
public class Publication
{
[Key]
public int PublicationID { get; set; }
public string PublicationTitle { get; set; }
public string Frequency { get; set; }
public DateTime NextIssueDate { get; set; }
public DateTime SpaceDeadline { get; set; }
public DateTime MaterialsDeadline { get; set; }
[JsonIgnore]
public DateTime CreatedDt { get; set; }
[JsonIgnore]
public string CreatedBy { get; set; }
[JsonIgnore]
public DateTime UpdatedDt { get; set; }
[JsonIgnore]
public string UpdatedBy { get; set; }
}
as Craig W. said you can use viewmodel ,also you can use anonymous type
(notice viewmodel is better way because you can use some utilities like automapper for mapping your property automatically)
JsonIgnore annotation has worked for me
[JsonIgnore]
public int Ranking { get; set; }
Here is a great article (Dec 2019) on the subject. It offers a solution for data shaping by making use of ExpandoObject and Type Reflection. The properties that the client requires can then be passed through the request as a query parameter (i.e. separated by a comma). The article also offers solution to the JSON Serialization problem.
Startup.cs file:
services.AddControllers(config =>
{
config.RespectBrowserAcceptHeader = true;
config.ReturnHttpNotAcceptable = true;
})
.AddXmlDataContractSerializerFormatters()
.AddNewtonsoftJson();
+1 for Sinaesthetic's answer.
I just finished reading an article, about GraphQL which solves exactly this problem. You can define exactly which fields do you need in the same request. No need for creating new endpoints every single time, when the caller needs just a specific subset of the properties.
If you can do this in .NET WEB API too without creating new models and endpoints, with just a very little extra effort, why wouldn't you (instead of exchanging Web Api for GraphQL).
Actually his SelectiveSerializer could be upgarded with reflection, so if you want to define which props you need in
C#, you can do this by providing property expressions, so you don't have to worry about misstyping prop names.
I bet there are other solutions for this, but the basic concept is the most important that we can define which fields we need in our json without creating new models.
Am new to programming and ASP.net MVC 3 so don't be surprised by my lack of knowledge on this.. Okay, I want to multiply two decimals, One decimal comes from the form that a user fills and the other decimal comes from the Model class (gets it from the database).
I have two Model classes called RATE & PROJECTMATERIAL . The RATE class has an item called Amount that states the amount of a Rate and the PROJECTMATERIAL class has an item quantity. The classes are related and i want to be able to say variable1 = quantity*Rates.amount and return variable1 to the my Index, Delete, Details views. I don't want to store variable1 to my database but i just want to display in my views.....but i don't know how and where to do it
Code from Project material class..
public class ProjectMaterial
{
public int ProjectMaterialID { get; set; }
[Required]
[Display(Name = "Scope Name")]
public int? ScopeID { get; set; }
[Required]
[Display(Name = "Rate Code")]
public int? RateID { get; set; }
[Required]
[Display(Name = "Quantity")]
public decimal Quantity { get; set; }
public virtual Scope Scopes { get; set; }
public virtual Rate Rates { get; set; }
}
Code from scope class..
public class Rate
{
public int RateID { get; set; }
[Required]
[Display(Name = "Rate Code")]
public int RateCode { get; set; }
[Required]
[Display(Name = "Unit")]
public string Unit { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required]
[Display(Name = "Amount")]
public decimal Amount { get; set; }
public virtual ICollection<ProjectMaterial> ProjectMaterials { get; set; }
}
Code from project controller class...
public class ProjectMaterialController : Controller
{
private ContructorContext db = new ContructorContext();
//
// GET: /ProjectMaterial/
public ViewResult Index()
{
var projectmaterials = db.ProjectMaterials.Include(p => p.Scopes).Include(p => p.Rates);
return View(projectmaterials.ToList());
}
//
// GET: /ProjectMaterial/Details/5
public ViewResult Details(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
return View(projectmaterial);
}
//
// GET: /ProjectMaterial/Create
public ActionResult Create()
{
ViewBag.ScopeID = new SelectList(db.Scopes, "ScopeID", "ScopeName");
ViewBag.RateID = new SelectList(db.Rates, "RateID", "Unit");
return View();
}
//
// POST: /ProjectMaterial/Create
[HttpPost]
public ActionResult Create(ProjectMaterial projectmaterial)
{
if (ModelState.IsValid)
{
db.ProjectMaterials.Add(projectmaterial);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ScopeID = new SelectList(db.Scopes, "ScopeID", "ScopeName", projectmaterial.ScopeID);
ViewBag.RateID = new SelectList(db.Rates, "RateID", "Unit", projectmaterial.RateID);
return View(projectmaterial);
}
//
// GET: /ProjectMaterial/Edit/5
public ActionResult Edit(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
ViewBag.ScopeID = new SelectList(db.Scopes, "ScopeID", "ScopeName", projectmaterial.ScopeID);
ViewBag.RateID = new SelectList(db.Rates, "RateID", "Unit", projectmaterial.RateID);
return View(projectmaterial);
}
//
// POST: /ProjectMaterial/Edit/5
[HttpPost]
public ActionResult Edit(ProjectMaterial projectmaterial)
{
if (ModelState.IsValid)
{
db.Entry(projectmaterial).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ScopeID = new SelectList(db.Scopes, "ScopeID", "ScopeName", projectmaterial.ScopeID);
ViewBag.RateID = new SelectList(db.Rates, "RateID", "Unit", projectmaterial.RateID);
return View(projectmaterial);
}
//
// GET: /ProjectMaterial/Delete/5
public ActionResult Delete(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
return View(projectmaterial);
}
//
// POST: /ProjectMaterial/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
db.ProjectMaterials.Remove(projectmaterial);
db.SaveChanges();
return RedirectToAction("Index");
}
Thanx in advance guys!! really need your help.
Seeing as you say you're new to MVC, I've given you a few options and explained which is best and why, because it's better to understand now so you don't get in to bad habits, especially if you start building larger projects.
You don't necessarily need to create a variable, because you can do that calculation in your view. Because you are passing the domain model directly to the view you can do (in razor):
#(Model.Quantity * Model.Rates.Amount)
Although this is the easiest option I wouldn't necessarily recommend this as views should be dumb - see ASP.NET MVC: How dumb should my view be?.
Another option is to do the calculation in the controller and pass the value in the ViewBag, e.g.:
public ViewResult Details(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
ViewBag.Price = projectmaterial.Quantity * projectmaterial.Rates.Amountl
return View(projectmaterial);
}
Then you could use it in your view like:
#ViewBag.Price
Again, this is easy but I wouldn't recommend it, as ViewBag isn't strongly typed - see Is using ViewBag in MVC bad?.
You could put a property on your ProjectMaterial class like, which is a neat solution.
public decimal Price
{
get
{
return Quantity * Rates.Amount;
}
}
However, if Price is a property that is only ever used within your views (ie you just display it) then it probably shouldn't be in your domain model, as your domain model is just that - storing and accessing the raw data.
Maybe the best way is to create a viewmodel specific to your view (see http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx) with a Price propert. This means that the property is only used where it is needed, the domain model remains just that, your view remains dumb and your domain model is not exposed to your view. See Why Two Classes, View Model and Domain Model? also for a good explanation of view models
You could add a property to your ProjectMaterial model:
public decimal Price
{
get
{
return Quantity * Rates.Amount;
}
}
You might want to have a model function with instances of your self.rate, and self.material items passed on from your views. Or otherwise you can individually calculate the values of the multiplication in each view.
Either way, you should be able to store the copy over the value of multiplication (variable1) in the view's bag, and pass it onto each view without having to save it in the DB.
ViewBag.variable1 = rate*material
return View()
#(int.Parse(variable) * your value)
Additional to all the answers you can use Data Format String in model class, and Html Helper in View to maintain formatting in displayed results for numeric types, by modifying returned attribute in the Controller.
The purpose of applying the formatting in the model class, and the value transformation in the controller and keeping the view standard, is to achieve separation of concerns (SoC) for easier maintenance, and control over the code.
Consider this example:
Products Class Property
[Display(Name = "Max Disc %")]
[DisplayFormat(DataFormatString = "{0:P1}", ApplyFormatInEditMode = true)]
public decimal MaxDiscountRate { get; set; }
Products Controller
[HttpGet]
public ActionResult Details(int id)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Products products = _uow.Products.GetById(id);
if (products == null)
{
return HttpNotFound();
}
else
{
products.MaxDiscountRate /= 100;
}
return View(products);
}
Products Details View
<div class="detail">
<h5 class="text-teal">#Html.DisplayNameFor(model => model.MaxDiscountRate)</h5>
<span class="text-peru">#Html.DisplayFor(model => model.MaxDiscountRate)</span>
</div>
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)