ASP. NET Ядро NullReferenceException После публикации формы - PullRequest
0 голосов
/ 31 января 2020

Я получаю исключение NullReferenceException при отправке формы обратно на сервер. Я использую ADO. NET с ASP. NET Core 3

Ниже приведена модель для кемпингов:

public class Campground
{
    public int ID { get; set; }

    [Required]
    [MaxLength(200)]
    [Display(Name = "Campground Name")]
    public string CampgroundName { get; set; }

    [Required]
    public int State { get; set; }
    public List<State> States { get; set; }

    [Required]
    public int Peak { get; set; }
    public List<Month> Months { get; set; }

    [Required]
    public string Overview { get; set; }

    [Required]
    [Display(Name = "Season Date From")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/YYYY}")]
    [DataType(DataType.Date)]
    public DateTime? SeasonDateFrom { get; set; }

    [Required]
    [Display(Name = "Season Date To")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/YYYY}")]
    [DataType(DataType.Date)]
    public DateTime SeasonDateTo { get; set; }


    [Display(Name = "Natural Features")]
    public string NaturalFeatures { get; set; }

    public string Recreation { get; set; }

    public string Facilities { get; set; }

    [Required]
    [Display(Name = "Campground Photo")]
    public string ImagePath { get; set; }
}

Я также создал ViewModel и назвал его CampgroundDetails:

 public class CampgroundDetails : Campground
{
    [Required]
    [Display(Name = "Campground Image")]
    public IFormFile Photo { get; set; }
}

Я пробовал разные подходы, но не могу двигаться дальше из-за этой ошибки. Ваша помощь очень ценится.

Вот метод HttpGet of Create:

 [HttpGet]
    public IActionResult Create()
    {
        CampgroundDetails campgroundDetails = new CampgroundDetails();
        List<State> states = new List<State>();
        List<Month> months = new List<Month>();

        using (SqlConnection connection = new SqlConnection(ConnectionString.DBCS))
        {
            using (SqlCommand command = new SqlCommand("sp_GetStates_Months", connection))
            {
                command.CommandType = CommandType.StoredProcedure;
                if (connection.State == ConnectionState.Closed)
                    connection.Open();
                using (SqlDataAdapter ada = new SqlDataAdapter(command))
                {
                    DataSet ds = new DataSet();
                    ada.Fill(ds);

                    DataTable statesDataTable = ds.Tables[0];
                    foreach(DataRow row in statesDataTable.Rows)
                    {
                        states.Add(new State()
                        {
                            ID = Convert.ToInt32(row["ID"]),
                            StateName = row["StateName"].ToString()
                        });
                    }
                    campgroundDetails.States = states;

                    DataTable monthsDataTable = ds.Tables[1];
                    foreach(DataRow row in monthsDataTable.Rows)
                    {
                        months.Add(new Month()
                        {
                            ID = Convert.ToInt32(row["ID"]),
                            MonthName = row["Month"].ToString()
                        }); ;
                    }
                    campgroundDetails.Months = months;
                }
            }
        }
        return View(campgroundDetails);
    }

Вот метод HttpPost of Create:

[HttpPost]
    public IActionResult Create(CampgroundDetails campgroundDetails)
    {
        if (ModelState.IsValid)
        {
            string filePath = UploadFile(campgroundDetails);

            using (SqlConnection connection = new SqlConnection(ConnectionString.DBCS))
            {
                using (SqlCommand command = new SqlCommand("sp_InsertNewCampground", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@CampgroundName", campgroundDetails.CampgroundName);
                    command.Parameters.AddWithValue("@State", campgroundDetails.State);
                    command.Parameters.AddWithValue("@Peak", campgroundDetails.Peak);
                    command.Parameters.AddWithValue("@SeasonDateFrom", campgroundDetails.SeasonDateFrom);
                    command.Parameters.AddWithValue("@SeasonDateTo", campgroundDetails.SeasonDateTo);
                    command.Parameters.AddWithValue("@NaturalFeatures", campgroundDetails.NaturalFeatures ?? "");
                    command.Parameters.AddWithValue("@Recreation", campgroundDetails.Recreation ?? "");
                    command.Parameters.AddWithValue("@Facilities", campgroundDetails.Facilities ?? "");
                    command.Parameters.AddWithValue("@ImagePath", filePath);
                    command.Parameters.AddWithValue("@Overview", campgroundDetails.Overview);

                    if (connection.State == ConnectionState.Closed)
                        connection.Open();

                    command.ExecuteNonQuery();
                }
            }
            return RedirectToAction("index", "home");
        }

        return View();
    }

Вот ошибка Я получаю:

enter image description here

1 Ответ

0 голосов
/ 31 января 2020

Я нашел решение своей проблемы, потому что я сделал загрузку файла обязательным

...