Search code examples
asp.netasp.net-mvcasp.net-coreasp.net-mvc-4

ASP MVC does not validate model


There is a simple view:

@model Bla.SomeModel

<div class="soket-item">
    <form>
        <div class="form-group socket-info-group">
            <label asp-for="Count" class="control-label"></label>
            <input name="Sockets[@index].Count" asp-for="Count" class="form-control" />
            <span asp-validation-for="Count" class="text-danger"></span>
        </div>
        <input type="submit" value="Push!" />
    </form>
</div>

And there is a simple model :

public class SomeModel
{
    [Required]
    [Display(Name = "Charge Count")]
    [Range(1, 10)]
    public int Count { get; set; }
}

enter image description here

As I set Range attribute I expect a warning to appear when a negative value entering. But that doesn't happen. Why ?

enter image description here

UPD Controller :

namespace Bla.Controllers
{
    [Route("Socket")]
    public class MyController : Controller
    {
        [Route("New")]
        public ActionResult NewSocketForm()
        {
            return View();
        }
    }
}

Solution

  • Here is the updated code:

    Code for UI

    @model SomeModel
    
    <div class="soket-item">
        <form asp-controller="Home" asp-action="New" method="post" >
            <div class="form-group socket-info-group">
                <label asp-for="Count" class="control-label"></label>
                <input name="Count" type="text" asp-for="Count" class="form-control" />
                <span asp-validation-for="Count" class="text-danger"></span>
            </div>
            <input type="submit" value="Push!" />
        </form>
    </div>
    

    Code for Controller

    [HttpPost]
    public IActionResult New(SomeModel someModel)
    {
        if (!ModelState.IsValid)
        {
            ViewBag.ErrorMessage = "Invalid Input";
        }
        // do your things
        return View("Index");
    }