Click here to Skip to main content
14,391,598 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am new in MVC and i need to fill database values to dropdownlist and while save i need to save dropdownselected item to database.
My code

View

<div class="editor-label">
                @Html.LabelFor(model => model.TaxID)
            </div>
            <div class="editor-field">
                @Html.DropDownList("Tax", "select Tax class")
                @Html.ValidationMessageFor(model => model.TaxID)
            </div>


controller for loading values from database to Dropdown

ViewBag.Tax = new SelectList(db.SHP_Taxes, "TaxID", "TaxName");


for Save in controller

[HttpPost]
        public ActionResult NewProduct(Product newProduct)
        {
                        if (ModelState.IsValid)
            {
                try
                {
                    SHP_Product pro = new SHP_Product();
                    var max = db.SHP_Products.Select(x => x.ProductID).Max();
                    int inter = Convert.ToInt32(max);
pro.TaxID = newProduct.TaxID;
  }
                catch (MembershipCreateUserException e)
                {


                }
            }
            ModelState.AddModelError("", "error occured");
            // If we got this far, something failed, redisplay form
            return View(newProduct);
        }


in controller model.taxid is null
Posted
Comments
[no name] 19-Nov-14 6:11am
   
Please debug for the get method. In the view you must return the UserID and other model properties for the data to load and available in the form/view.
Please check post back your comments.
Nathan Minier 19-Nov-14 7:53am
   
Instead of:
@Html.DropDownList("Tax", "select Tax class")
@Html.ValidationMessageFor(model => model.TaxID)

Try:
@Html.DropDownListFor(model => model.TaxID, ViewBag.Tax)
@Html.ValidationMessageFor(model => model.TaxID)

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Thank you all

@Html.DropDownListFor(model => model.TaxID, (SelectList)ViewBag.Tax)


This one worked out for me. thank u Nathan Minier..
   
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100