I am using asp.net core with razor engine on the front end and entity framework on the back end. The problem I am having is when I submit my form all the data I entered shows up as null in my method.
Here is my HTML Code where the user enters the info.
@model craigslist.Models.Auto
<form asp-controller="Auto" asp-action="AddAuto" method="post" role="form">
<span asp-validation-for="Make"></span>
<label asp-for="Make"></label>
<input asp-for="Make"/>
<span asp-validation-for="Model"></span>
<label asp-for="Model"></label>
<input asp-for="Model"/>
<label asp-for="Part"></label>
<input asp-for="Part"/>
<label asp-for="Price"></label>
<input asp-for="Price"/>
<button type="submit">Add Auto or Part</button>
</form>
Here is the C# controller class method that is going to input the data in my db.
[HttpPost]
[Route("addAuto")]
public IActionResult AddAuto(Auto model) //model always shows up as null
{
var user_id = HttpContext.Session.GetInt32("Id");
if(ModelState.IsValid)
{
Auto auto = new Auto();
auto.Make = model.Make;
auto.Model = model.Model;
auto.Part = model.Part;
auto.Price = model.Price;
auto.CreatedAt = DateTime.Now;
auto.UpdatedAt = DateTime.Now;
auto.UserId = (int)user_id;
_context.Auto.Add(auto);
_context.SaveChanges();
return RedirectToAction("AutoInfo");
}
return View("Auto", model);
}
Here is my model for Auto
using System;
using System.ComponentModel.DataAnnotations;
namespace craigslist.Models
{
public class Auto
{
public int Id { get; set; }
[MinLength(3)]
[Required(ErrorMessage ="Please enter your make")]
public string Make { get; set; }
[MinLength(3)]
[Required(ErrorMessage ="Please enter your model")]
public string Model { get; set; }
public string Part { get; set; }
[Required(ErrorMessage ="Please enter your price")]
public int Price { get; set; }
public int UserId {get; set;}
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
}
Since Auto model
in my controller always shows up as null nothing is ever added to my db. What am I doing wrong?