我已經看到了一堆這些帖子,但沒有人幫助我,因爲大多數沒有應用於C#和MVC。對象引用未設置爲對象的實例MVC
我有一個名爲TipoImovel的對象的Create。這個對象有一個自動生成的ID(int),一個描述(字符串 - tipoImovel),然後將可能的NULL值賦給一個sub-TipoImovel(int?然後是參考TipoImovel)。如果覺得混亂,就像創建House(TipoImovel)一樣。然後,您可以創建一個Pool(也稱爲TipoImovel),並說它是TipoImovel的一個子類型,使其成爲House(Pool with House)的subTipoImovel的Pool。對不起,我的母語是他們的名字。如果周圍出現任何問題,請說。
現在,這裏的代碼:
TipoImovel.cs
public class TipoImovel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Display(Name = "Tipo de Imóvel")]
[StringLength(20)]
public string tipoImovel { get; set; }
[Display(Name = "Sub-Tipo de:")]
public int? tipoImovelID { get; set; }
[Display(Name = "Sub-Tipo de:")]
public virtual TipoImovel subTipoImovel { get; set; }
}
TipoImovelController.cs(GET和POST方法)
// GET: TipoImovel/Create
public ActionResult Create()
{
ViewBag.tipoImovelID = new SelectList(db.TipoImovel, "ID", "tipoImovel");
return View();
}
// POST: TipoImovel/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,tipoImovel,tipoImovelID")] TipoImovel TipoImovel)
{
if (ModelState.IsValid)
{
db.TipoImovel.Add(TipoImovel);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.tipoImovelID = new SelectList(db.TipoImovel, "ID", "tipoImovel", TipoImovel.tipoImovelID);
return View(TipoImovel);
}
Create.cshtml
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TipoImovel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.tipoImovel, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.tipoImovel, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.tipoImovel, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.tipoImovelID, "tipoImovelID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("tipoImovelID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.subTipoImovel, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
的錯誤來了你因爲我在POST方法中收到的TipoImovel爲NULL。該表單已正確創建,可以通過Retineiving(手動引入)現有的TipoImovel並在ComboBox中顯示它們,但在點擊「創建」時會崩潰。
我一直在解決這個問題2天,我無法修復它。任何幫助表示讚賞!
編輯:生成的HTML的圖片:
哪一行發生錯誤? – markpsmith
ViewBag.tipoImovelID = new SelectList(db.TipoImovel,「ID」,「tipoImovel」,TipoImovel.tipoImovelID); 這一個,但它不應該達到那裏。它應該輸入IF條款。 – Forget
整個參數在POST中是空的還是它的屬性? – Jonesopolis