0

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?

2
  • @Html.ValidationMessageFor with @Html.TextAreaFor, @Html.TextBoxFor and @Html.DropDownListFor should be used if you're using a viewmodel class, and mark corresponding properties as [Required(ErrorMessage = "This field can't be empty")]. Commented Jan 4, 2018 at 9:13
  • @TetsuyaYamamoto I already sue your code, but I got error in this line @Html.DropDownList("jenis1", ViewBag.jenisList as SelectList, "--Jenis--", new { required = "required" }) if a column name is empty, maybe my return is wrong but I dont know how to fix this Commented Jan 5, 2018 at 1:12

2 Answers 2

2

You can use like below to validate error thorugh model

[Required (ErrorMessage= "jenis selection is Required")]  
public string jenisList { get; set; }

and if you want to bind drop down list using viewbag, just use Viewbag in your related action method in controller.

[HttpGet]
public ActionResult SetDataInDataBase()
{
    ViewBag.jenisList  = new SelectList(db.isengs, "jenis", "jenis");
    return View();
}

Write below code in view

@Html.DropDownList("jenis", (SelectList)ViewBag.jenisList  , "-- Choose --")
@Html.ValidationSummaryFor(model => model.jenisList, "", new { @class = "text-danger" })
Sign up to request clarification or add additional context in comments.

2 Comments

I already sue your code, but I got error in this line @Html.DropDownList("jenis1", ViewBag.jenisList as SelectList, "--Jenis--", new { required = "required" }) if a column name is empty, maybe my return is wrong but I dont know how to fix this
try now hope its help you :)
1

This is example how you can use validation with a strongly-typed viewmodel bound to view:

Model

public class CostVM
{
   // required property attribute
   [Required(ErrorMessage = "This field can't be empty")]
   public string Name { get; set; }

   // other properties
}

View

@model CostVM

@Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)

If you want to show all validation errors, use validation summary feature:

@Html.ValidationSummary()

Reference: Performing Simple Validation

3 Comments

I used your code, but I got error in this line @Html.DropDownList("jenis1", ViewBag.jenisList as SelectList, "--Jenis--", new { required = "required" })
@Ihsan if you want to bind to model best way to do that is to use DropDownListFor(m => m.JenisList.....) But if you still want to use DropDownList("name") the 'name' should be exactly the same as property in your model.
wouldnt it show error when user first loads the view as model.Name will be blank the first time (get request)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.