0

I have Product Model in ProductCreate view and I am sending product property data from view to controller to ProductCreate Action, but in the controller I get null Product paramater, all Product model properties are null.

What is wrong with my code? Thanks for your helps.

here is my coding. I use FormCollection for Specification(named here Ozellik) data collection.

Product Model

public class Product : EntityBase
{
    public Product()
    {
        this.Photos = new List<Photo>();
        this.OrderDetails = new List<OrderDetail>();
        this.Suppliers = new List<Supplier>();
        this.Comments = new List<Comment>();
        this.Ozelliks = new List<Ozellik>();
    }

    [MaxLength(100, ErrorMessage = "Max 100 karakter."), Required]
    public string Name { get; set; }
    [Required]
    public decimal BuyingPrice { get; set; }
    [Required]
    public decimal SalesPrice { get; set; }
    [Required]

    public decimal DiscountedPrice { get; set; }
    public decimal VATRatio { get; set; }
    [MaxLength(250, ErrorMessage = "Max 3050 karakter."), Required]
    public string DescriptionLong { get; set; }
    [MaxLength(250, ErrorMessage = "Max 250 karakter."), Required]
    public string DescriptionShort { get; set; }
    [MaxLength(250, ErrorMessage = "Max 250 karakter."), Required]
    public string Brand { get; set; }
    [Required]
    public string Size { get; set; }
    public Gender Gender { get; set; }
    public Color Color { get; set; }
    public bool IsActive { get; set; }
    public decimal? Discount { get; set; }
    public int StockQuantity { get; set; }
    public int LineNumber { get; set; }
    public float CommentAvg { get; set; }
    public bool IsNew { get; set; }
    public string CategoryName { get; set; }

    public virtual Mainproduct Mainproduct { get; set; }
    public virtual List<Campaign> Campaigns{ get; set; }
    public virtual List<OrderDetail> OrderDetails { get; set; }
    public virtual List<Supplier> Suppliers { get; set; }
    public virtual List<Photo> Photos { get; set; }
    public virtual List<Comment> Comments { get; set; }
    public virtual List<Ozellik> Ozelliks { get; set; }
}

my controller ProductCreate Action

 [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "Admin")]
    public ActionResult ProductCreate(Product Product, FormCollection form)
    {

        var itemno = 1;

        for (int i = 2; i == form.Count; i++)
        {
            string name = "Name" + itemno;
            string description = "Description" + itemno;
            string isactive = "IsActive" + itemno;

            db.Ozelliks.Add(new Ozellik
            {
                ProductId = Product.Id,
                Name = form["name"].ToString(),
                Description = form["description"].ToString(),
                IsActive = Convert.ToBoolean(form["isactive"])
            });
            itemno++;
            db.SaveChanges();
        }

        Product.DiscountedPrice = Product.SalesPrice * (1 - System.Convert.ToDecimal(Product.Discount) / 100);
        db.Products.Add(Product);
        db.SaveChanges();
        ViewBag.CurrentUser = db.Users.Find(WebSecurity.CurrentUserId);
        return RedirectToAction("ProductIndex");
    }

and my ProductCreate view

@model Product
@{
ViewBag.Title = "Yeni Ürün Giriş";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}


@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<header class="page-header">
    <div class="container-fluid">
        <h2 class="no-margin-bottom">Yeni Ürün Ekle</h2>
    </div>
</header>
<!-- Breadcrumb-->
<div class="breadcrumb-holder container-fluid">
    <!--<ul class="breadcrumb">
      <li class="breadcrumb-item"><a href="index.html">Home</a></li>
      <li class="breadcrumb-item active">Forms            </li>
    </ul>-->
</div>
<!-- Forms Section-->
<section class="forms">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header d-flex align-items-center">
                        <h3 class="h4">Ürün Bilgileri</h3>
                    </div>
                    <div class="card-body">
                        <form class="form-horizontal">
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">Ürün Adı</label>
                                <div class="col-sm-9">
                                    <input type="text" name="Name" class="form-control">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label"><br><small class="text-primary"></small></label>
                                <div class="col-sm-9">
                                    <div class="i-checks">
                                        <input id="checkboxCustom1" type="checkbox" value="" name="IsNew" class="checkbox-template">
                                        <label for="checkboxCustom1">Yeni Ürün Etiketi Olsun Mu?</label>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header d-flex align-items-center">
                        <h3 class="h4">Fiyat</h3>
                    </div>
                    <div class="card-body">
                        <form class="form-inline" style="text-align:center">
                            <label class="col-sm-3 form-control-label"><br><small class="text-primary"></small></label>
                            <table>
                                <tr>
                                    <td>Alış Fiyatı</td>
                                    <td>Satış Fiyatı</td>
                                </tr>
                                <tr>
                                    <td><input id="inlineFormInput" type="number" name="BuyingPrice" step="any" min="1" class="mr-3 form-control"></td>
                                    <td><input id="inlineFormInput" type="number" name="SalesPrice" step="any" min="1" class="mr-3 form-control"></td>
                                </tr>
                            </table>
                        </form>
                        <br />
                        <form class="form-inline" style="text-align:center">
                            <label class="col-sm-3 form-control-label"><br><small class="text-primary"></small></label>
                            <table>
                                <tr>
                                    <td>İndirim Oranı</td>
                                    <td>İndirimli Satış Fiyatı</td>
                                </tr>
                                <tr>
                                    <td><input id="inlineFormInput" type="number" name="Discount" step="any" min="1" class="mr-3 form-control"></td>
                                    <td><input id="inlineFormInput" type="number" name="DiscountedPrice" step="any" min="1" class="mr-3 form-control"></td>
                                </tr>
                            </table>
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header d-flex align-items-center">
                        <h3 class="h4">Açıklama</h3>
                    </div>
                    <div class="card-body">
                        <form class="form-horizontal">
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">Kısa Ürün Açıklaması</label>
                                <div class="col-sm-9">
                                    <input type="text" name="DescriptionShort" class="form-control">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">Uzun Ürün Açıklaması</label>
                                <div class="col-sm-9">
                                    <input type="text" name="DescriptionLong" class="form-control">
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header d-flex align-items-center">
                        <h3 class="h4">Diğer</h3>
                    </div>
                    <div class="card-body">
                        <form class="form-horizontal">
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">Marka</label>
                                <div class="col-sm-3">
                                    <input type="text" name="Brand" class="form-control">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">KDV</label>
                                <div class="col-sm-3">
                                    <input type="text" name="VATRatio" class="form-control">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">Kategori</label>
                                <div class="col-sm-9 select">
                                    <select name="CategoryName" class="form-control">
                                        @foreach (var item in (IEnumerable<SelectListItem>)ViewBag.Categories)
                                        {
                                            <option value=@item.Value id="CategoryName">@item.Text</option>
                                        }
                                    </select>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">Cinsiyet</label>
                                <div class="col-sm-9  select">
                                    @Html.DropDownListFor(model => model.Gender, new SelectList(Enum.GetValues(typeof(IcatSite.Models.Gender))))
                                </div>
                            </div>
                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">Tedarikçiler <br><small class="text-primary"></small></label>
                                <div class="col-sm-9">
                                    <div>
                                        <select name="Suppliers" class="form-control">
                                            @foreach (var item in (IEnumerable<Supplier>)ViewBag.Suppliers)
                                            {
                                                <option value=@item.Id id="Suppliers">@item.CompanyName</option>
                                            }
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group row">
                                <label class="col-sm-3 form-control-label">Aktif mi?</label>
                                <div class="col-sm-6">
                                    <div class="i-checks" style="width:60px;float:left;margin-right:10px">
                                        <input id="radioCustom1" type="radio" checked="checked" value=true name="IsActive" class="radio-template">
                                        <label for="radioCustom1">Aktif</label>
                                    </div>
                                    <div class="i-checks">
                                        <input id="radioCustom2" type="radio" value=false name="IsActive" class="radio-template">
                                        <label for="radioCustom2">Pasif</label>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header d-flex align-items-center">
                        <h3 class="h4">Ürün Özellikleri</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group row">
                            <div class="col-lg-8">
                                <table class="table table-striped table-sm" id="ozellik">
                                    <tr>
                                        <td>Özellik</td>
                                        <td>Değer</td>
                                        <td style="width:80px">Aktif mi?</td>
                                    </tr>
                                    <tr>
                                        <td><input type="text" name="Name0" value=" " /></td>
                                        <td><input type="text" name="Description0" value=" " /></td>
                                        <td><input type="checkbox" checked="checked" value="True" name="IsActive0"></td>
                                    </tr>
                                </table>
                                <br />
                                <div class="box-footer">
                                    <button type="button" id="ozellikbutton" class="btn btn-default">Yeni Özellik Ekle</button>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

                <div class="box-footer">
                    <button type="submit" class="btn btn-primary">Kaydet</button>
                </div>

            </div>
        </div>
    </div>
</section>
}


@section ozellikekle{
<script>
    $(document).ready(function () {
        var i = 1;
        $('#ozellikbutton').click(function () {
            $('#ozellik tr:last').after('<tr><td><input type="text" value=" "/></td><td><input type="text" value=" " /></td><td><input type="checkbox" value=" " /></td></tr>');
            var name = "Name" + i;
            var description = "Description" + i;
            var isactive = "IsActive" + i;
            $('#ozellik tr:last td:nth-child(1) input:nth-of-type(1)').attr("name", name);
            $('#ozellik tr:last td:nth-child(2) input:nth-of-type(1)').attr("name", description);
            $('#ozellik tr:last td:nth-child(3) input:nth-of-type(1)').attr("name", isactive);
            $('#ozellik tr:last td:nth-child(3) input:nth-of-type(1)').attr("checked", "checked");
            i++;
        });
    });
</script>

}
livefreeor
  • 109
  • 12
  • It seems you wanting to dynamically add collection items, in which case refer the answers [here](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) and [here](http://stackoverflow.com/questions/40539321/partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) –  Jan 16 '18 at 22:24
  • Actually I dont have any problem with FormCollection, it works well there but I have problem with Product model property data. When I submit, I get product paramater null in controller. Nothing in product model names match with names in the view. normally it should match with name attribute. Am I wrong? thanks for your help. – livefreeor Jan 16 '18 at 22:58
  • Why in the world are you generating manual html like that instead of binding to your model. And some of your code wont bind - how would you expect your checkbox with `value=""` to bind to a `bool` for example. You also have nested forms which is invalid html and not supported. (and read the links I gave you - never use `FormCollection` in MVC). –  Jan 16 '18 at 23:07
  • thanks @stephenMuecke . the reason I wanted to use FormCollection I have product specifications. Number of specification chance for each product. I wanted to add as many as needed in product creatation page. I also tried without FormCollection to check if i can get model parameter full but still I get model parameters null in the controller. I will also edit empty value are. Thanks for your help. – livefreeor Jan 16 '18 at 23:26
  • Yes I know. Which is why I gave you 2 links to show you how to do it correctly :) –  Jan 16 '18 at 23:30
  • And get rid of your nested forms. Then delete all this awful view code, and start again correctly by using `@Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name)` –  Jan 16 '18 at 23:34

0 Answers0