hi
I put dropdownlist in View to insert selected Item's Id into database below are codes:
public partial class Reseller
{
public int Id { get; set; }
public string Name { get; set; }
public int OstanId { get; set; }
public Nullable<int> CityId { get; set; }
public string Address { get; set; }
public string OstanName { get; set; }
public string CityName { get; set; }
public virtual City City { get; set; }
public virtual Ostan Ostan { get; set; }
}
view model:
public class AddResellerViewModel
{
public Reseller Reseller { get; set; }
public List<SelectListItem> Ostans { get; set; }
public string OstanName { get; set; }
}
controller:
[HttpGet]
public ActionResult AddReseller()
{
var model = new AddResellerViewModel();
model.Ostans = PopulateOstan();
return View(model);
}
[HttpPost]
public ActionResult AddReseller(Reseller reseller)
{
SqlConnection constr = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Constring"].ConnectionString);
using (SqlCommand cmd = new SqlCommand("InsertReseller", constr))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = constr;
constr.Open();
cmd.Parameters.AddWithValue("@Name", reseller.Name);
cmd.Parameters.AddWithValue("@Address", reseller.Address);
cmd.Parameters.AddWithValue("@Ostanid", reseller.OstanId);
cmd.ExecuteNonQuery();
constr.Close();
}
return View();
}
View:
@model MvcInternetShop.ViewModels.Test.AddResellerViewModel
@using (Html.BeginForm("AddReseller", "Test", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="group">
@Html.LabelFor(model => model.Reseller.OstanId, new { @class = "label" })
<div class="controls">
@Html.DropDownListFor(model => model.Reseller.OstanId, new SelectList((List<SelectListItem>)Model.Ostans, "Value", "Text"), "please Select")
@Html.ValidationMessageFor(model => model.Reseller.OstanId)
</div>
</div>
ERROR:
Additional information: Object reference not set to an instance of an object.
but I put breakpoint on
[HttpPost] public ActionResult AddReseller(Reseller reseller) {
and I checked this line:
cmd.Parameters.AddWithValue("@Ostanid", reseller.OstanId);
and it has selected Item Id value.