简体   繁体   中英

How can I post data in database by showing data from another table in Dropdownlist

I am having a problem with my View. I have a Product Model and I want to add products. In it, there is a dropdownlist of category Name which is coming from another model. I want to select the category and then get the ID of that Category and put it in my Product Model Because it had a foreign key of that category. Basically, I want the category name to be shown as well as if someone selects it .it should post the Id of that Category so that I can put it in my product model.

This is My Product View

@using Test2.Models;
@model ViewModel

@{
    ViewBag.Title = "Product";
    Layout = "~/Views/Shared/masternav1.cshtml";


}

<h2>Product</h2>

<link href="~/Scripts/StyleSheet1.css" rel="stylesheet" />

@using (@Html.BeginForm("Product", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="container">
        <form action="action_page.php">

            <div class="imgcontainer">
                <img src="~/Content/Images/product.jpg" alt="Avatar" class="avatar" />

            </div>

       @Html.Partial("_AdminProduct",Model.Productmodel)


            @Html.DropDownListFor(model => model.Productmodel.pro_fk_cat, new SelectList(new string[] { "Select Category", Model.CategoryModel.CategoryName }, "Select Category"), htmlAttributes: new { @class = "form-control" })


              <div>  

                <br />
                <input type="submit" value="Sign Up" class="btn btn-success btn-block" />
                <span style="color:red;">@ViewBag.error </span>

            </div>

            <div class="container" style="background-color:#f1f1f1">
                <button type="button" class="cancelbtn">Cancel</button>
            </div>

        </form>
    </div>
}



This is my Product Partial VIew.

@model Test2.Models.Product

<div>
    <label for="uname"><b>Product Name</b></label>
    @*<input type="text" placeholder="Enter Username" name="uname" required="required">**@
    @Html.TextBoxFor(x => x.ProductName, new { @placeholder = "Product Name", @required = "required" })
    <br />
    <label for="psw"><b>Upload Image</b></label>
    @*<input type="password" placeholder="Enter Password" name="psw" required>*@
    <input type="file" name="Imgfile" id="Imgfile" class="form-control" required="required" />
    <br />
    <label for="psw"><b>Product Discription</b></label>
    @*<input type="password" placeholder="Enter Password" name="psw" required>*@
    @Html.TextAreaFor(x => x.ProductDes, new { @placeholder = "Product Discription", @required = "required", @class = "form-control" })
    <br />
    <label for="psw"><b>Product Price</b></label>
    @*<input type="password" placeholder="Enter Password" name="psw" required>*@
    @Html.TextBoxFor(x => x.Productprice, new { @placeholder = "Product Price", @required = "required" })
    <br />

    <label for="psw"><b>Product Category</b></label>
    @*@Html.DropDownListFor(x => x.pro_fk_cat, new SelectList(Model.),"Select Category")*@


</div>

This is my Controller

 public ActionResult Product()
        {
            if (Session["ad_id"] == null)
            {
                return RedirectToAction("AdminLogin");
            }
           ViewModel mymodel = new ViewModel();
            mymodel.CategoryData = GetCategory();
            mymodel.Productmodel = GetProduct();
            return View(mymodel);
        }
        [HttpPost]
        public ActionResult Product(Product p,HttpPostedFileBase Imgfile)
        {
            string path = uploadingfile(Imgfile);
            if (path.Equals("-1"))
            {
                ViewBag.error = "Image Could not be Uploaded";
            }
            else
            {
                Product pro = new Product();


                pro.ProductName = p.ProductName;
                pro.ProductImage = path;
                pro.ProductDes = p.ProductDes;
                pro.Productprice = p.Productprice;
                pro.pro_fk_ad = Convert.ToInt32(Session["ad_id"].ToString());
                pro.pro_fk_cat = p.pro_fk_cat;
                db.Products.Add(pro);

                db.SaveChanges();
                return RedirectToAction("Category");
            }

            return View();
        }

This is my product model


namespace Test2.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public string ProductImage { get; set; }
        public string ProductDes { get; set; }
        public int Productprice { get; set; }
        public Nullable<int> pro_fk_cat { get; set; }
        public Nullable<int> pro_fk_ad { get; set; }

        public virtual Admintb Admintb { get; set; }
        public virtual Category Category { get; set; }
    }
}

This is my Category Model


namespace Test2.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Category
    {
        public Category()
        {
            this.Products = new HashSet<Product>();
        }

        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
        public string CategoryImg { get; set; }
        public Nullable<int> CategoryAdminID { get; set; }

        public virtual Admintb Admintb { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }
}

This is my ViewModel which I am using to retrieve multiple models in a single View.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Test2.Models
{
    public class ViewModel
    {
        public IEnumerable<Admintb> AdminData { get; set; }
        public IEnumerable<Category> CategoryData { get; set; }

        public IEnumerable<Usertb> UserDt { get; set; }

        public Product Productmodel { get; set; }

        public Admintb Adminmodel { get; set; }

        public Usertb Usermodel { get; set; }

        public Category CategoryModel { get; set; }


        public Category Categryselection { get; set; }

    }


    public enum Category
    {

    }
} 

You just need to write a code in your controller that get the category name and return the Id.

Something like this:

myProduct.category = categories.FirstOrDefault(c=> c.Name == categoryName).Id;

when your categoryName is the category what the user chosen.

It's realy simple.

good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM