I'm having trouble using Html.ValidationMessage because I use ViewModel,
this is my Controller
public ActionResult SetDataInDataBase()
{
ViewData["jenisList"] = new SelectList(db.isengs, "jenis", "jenis");
return View();
}
[HttpPost]
public ActionResult SetDataInDataBase(CostVM model)
{
informasi item = new informasi();
if (model.nama == null)
{
ModelState.AddModelError("Error", "This Field Cant Empty");
return View(model);
}
else
{
item.nama = model.nama;
item.alamat = model.alamat;
item.jk = model.jk;
item.kelas = model.kelas;
item.jenis = model.jenis;
}
db.informasis.Add(item);
db.SaveChanges();
return RedirectToAction("Edit", "Register", new { id = item.id, id2 = item2.Id });
}
this is my RazorView
@Html.ValidationMessage("Error")
<div class="container">
<div class="form-group">
<label>Nama:</label>
@Html.TextArea("nama")
</div>
<div class="form-group">
<label>Alamat:</label>
<input class="form-control" name="alamat" placeholder="Enter Password" required/>
</div>
<div class="form-group">
<label>JK:</label>
<input class="form-control" type="radio" name="jk" value="L" required/>L<br />
<input class="form-control" type="radio" name="jk" value="P" />P<br />
</div>
<div class="form-group">
<label>Kelas:</label>
<select name="kelas" required>
<option value="">--Pilih Kelas--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="form-group">
<label>Jenis:</label>
<div >
@Html.DropDownList("jenis1", ViewBag.jenisList as SelectList, "--Jenis--", new { required = "required" })
</div>
</div>
<div class="button">
<button>Submit</button>
</div>
</div>
I want to make if model.name is empty, show a notice or Message error "This Field Can't Empty", but I dont understand because I use ViewModel
Can someone help me show Validation Message if model.name empty?
@Html.ValidationMessageForwith@Html.TextAreaFor,@Html.TextBoxForand@Html.DropDownListForshould be used if you're using a viewmodel class, and mark corresponding properties as[Required(ErrorMessage = "This field can't be empty")].@Html.DropDownList("jenis1", ViewBag.jenisList as SelectList, "--Jenis--", new { required = "required" })if a column name is empty, maybe myreturnis wrong but I dont know how to fix this