0

I am currently busy with an project where I do use ASP.NET MVC. When I try to post data to model and controller I am getting NULL returned in the parameter of the method I have used in the controller. Controller:

[HttpPost]
    public ActionResult Create(Company company)
    {
        if (ModelState.IsValid)
        {
            company.Visible = 1;
            company.Created = DateTime.Now;
            company.Updated = DateTime.Now;

            //Save company to database
            cm.AddCompany(company);
            cm.SaveChanges();

            //Redirect user to Index after created a company
            return RedirectToAction(nameof(Index));
        }
        else
        {
            return View();
        }
    }

My database first model:

        public Company()
    {
        this.Purchases = new HashSet<Purchase>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
    public string HouseNumber { get; set; }
    public string Zip { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string Mobile { get; set; }
    public string Email { get; set; }
    public string Branche { get; set; }
    public string KVKnumber { get; set; }
    public string BTWnumber { get; set; }
    public System.DateTime Created { get; set; }
    public Nullable<System.DateTime> Updated { get; set; }
    public Nullable<int> Visible { get; set; }

    public virtual ICollection<Purchase> Purchases { get; set; }

And the view where I have to send data to the model and controller:

@model  ExamenProject.Database.Company
<form asp-controller="Company" asp-action="Create" method="post" enctype="multipart/form-data">
                <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
                <div class="row">
                    <div class="col-md-12">
                        <fieldset>
                            <label asp-for="Name">Naam</label>
                            <div class="field">
                                <input asp-for="Name" class="form-control" style="margin-bottom:2%;" type="text"/>
                                <span asp-validation-for="Name" />
                            </div>
                        </fieldset>
                    </div>

I dont really know why the parameter company in my Create method always returns NULL.

  • Obviously model serialization wasn't successful. You can check raw request data is it correct – Fabio Mar 13 '17 at 10:38

1 Answers1

0

Try to add FromBody attribute in your controller method.

public ActionResult Create([FromBody]Company company)

Ygalbel
  • 5,214
  • 1
  • 24
  • 32