Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dropdown in mvc3 edit form

This maybe very simple but I cant seem to sort it out on my own. I have created a simple db and entity modal that looks like this

enter image description here

I am trying to create an Create form that allows me to add a new Order. I have a total of 3 tables so what I am trying to do is have the form allowing the person to enter Order date and also has a dropdown list that allows me to select a product from the product table

I want to be able to create a Add or Edit view that allow me to insert the OrderDate into the OrderTable and also insert the OrderID and selected ProductID into OrderProduct.

What steps do I need to do here.

I have created an OrderController and ticked the "Add Actions" and than added a Create View which looks like this

@model Test.OrderProduct

@{
    ViewBag.Title = "Create2";
}

    <h2>Create2</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>OrderProduct</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.OrderID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.OrderID)
            @Html.ValidationMessageFor(model => model.OrderID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductID)
            @Html.ValidationMessageFor(model => model.ProductID)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

This creates the view that contains a textbox for both OrderID and ProductID however no date.

My controller CreatePost hasnt been changed

  [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        try
        {
            var data = collection;
            // TODO: Add insert logic here
          //  db.Orders.AddObject(collection);
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

My questions are,

1.How do I swap out ProductID textbox to be a dropdown which is populated from Product 2.How do I get the data from FormCollection collection? I thought of just a foreach however I dont know how to get the strongly typed name

Any help for a newbie would be very helpful.

Thank you!

like image 298
Diver Dan Avatar asked Jan 28 '11 01:01

Diver Dan


2 Answers

First thing's first, don't bind to the Order entity. Never bind to an EF object, always try and use a ViewModel. Makes life simpler for the View, and that is the goal here.

So, have a ViewModel like this:

public class CreateOrderViewModel
{
   public int OrderId { get; set; }
   public DateTime OrderDate { get; set; }
   public int SelectedProductId { get; set; }
   public IEnumerable<SelectListItem> Products { get; set; }
}

That's it right now.

Return that to your View in your [HttpGet] controller action:

[HttpGet]
public ActionResult Create()
{
   var model = new CreateOrderViewModel
   {
      Products = db.Products
                   .ToList() // this will fire a query, basically SELECT * FROM Products
                   .Select(x => new SelectListItem
                    {
                       Text = x.ProductName,
                       Value = x.ProductId
                    });
   };

   return View(model);
}

Then to render out the list of Products: (basic HTML excluded)

@model WebApplication.Models.CreateOrderViewModel

@Html.DropDownListFor(model => model.SelectedProductId, Model.Products)

The only thing i don't know how to do is bind to the DateTime field. I'm guessing you would need an extension method (HTML Helper) which renders out a Date Picker or something. For this View (creating a new order), just default to DateTime.Now.

Now, onto the [HttpPost] controller action:

[HttpPost]
public ActionResult Create(CreateOrderViewModel model)
{
   try
   {
      // TODO: this manual stitching should be replaced with AutoMapper
      var newOrder = new Order
      {
         OrderDate = DateTime.Now,
         OrderProduct = new OrderProduct
         {
            ProductId = SelectedProductId
         }
      };

      db.Orders.AddObject(newOrder);
      return RedirectToAction("Index");
   }
   catch
   {
      return View();
   }
}

Now, i also think your EF model needs work.

To me (in English terms), a Product can have many orders, and an Order can have many Products.

So, it should be a many-to-many. Currently it's a 1-1 with a redundant join table. Did you generate that from a DB? If so, your DB possibly needs work.

You should have a navigational property called Products on the Order entity, which references a collection of Product, made possible by a silent join to the join table in the many-to-many.

This also means you no longer have a DropDownList, but a MultiSelectDropDownList.

like image 150
RPM1984 Avatar answered Oct 14 '22 05:10

RPM1984


Thanks Craig. Your few days (as at time of posting) of MVC have solved my few days of trying to get the selected value back from DropDownListFor.

I had no problem in the Create view in getting the selected value of the DDLF, but the Edit view was a completely different matter - nothing I tried would get the selected value back in the Post. I noticed the selected value was lurking in the AttemptedValue of the ModelState, and so Dr.Google referred me here.

I had this in my view

    @Html.DropDownList(model => model.ContentKeyID, Model.ContentKeys, Model.ContentKeyName)

where ContentKeys is a SelectList populated from the DB via a ViewModel, and ContentKeyName is the curently selected name.

The wierd thing is, I have another DDL on the view populated in an identical manner. This one works. Why, I don't know. It is the second DDL on the form, but I can't see that making a difference.

I read somewhere else it might have been that I was using Guids as the Id, but that didn't seem to make a difference - I changed to Int32, but don't think I had to - I think it's enums that disagree with DDLF. Nullables seemd to make no difference either.

Now that I've added the form collection to my Post ActionResult, and get the selected value using

-view

    @Html.DropDownList("ContentKey", Model.ContentKeys)

-in controller (Post)

    contentKeyId = int.Parse(form.GetValue("ContentKey").AttemptedValue); 

all is good, and I can get on with more exciting things. Why is that the simplest things can hold you up for so long?

like image 30
Rob Avatar answered Oct 14 '22 06:10

Rob