ProtoCUS
ProtoCUS

Reputation: 49

Validation Message MVC

My code is as followed and the error message are not displayed:

Index.cshtml

@model WebApp.Models.OrderItems
@using (Html.BeginForm("SaveToDB", "Home", FormMethod.Post, new { @class = "form-group", role = "form" }))
{

@Html.Partial("Information")

}

Partial : Information.cshtml

@model WebApp.Models.OrderItems

<div class="col-lg-4">
    <div class="form-group">
        <label for="input1" class="col-lg-4 control-label">@Html.LabelFor(model => model.CLInfo.ClientName)</label>
        @Html.EditorFor(model => model.CLInfo.ClientName, new { style = "width:250px" })
        @Html.ValidationMessageFor(model => model.CLInfo.ClientName)
    </div>
</div>

Model :

public class OrderItems
 {
      public InfoCLInfo{ get; set; }
 }

Model : the class for Infos

public class Info
 {
     [Display(Name = "Client Name")]
     [Required]
     public string ClientName{ get; set; }    
 }

The controller

    [HttpPost]
    [MultipleButton(Name = "action", Argument = "SaveToDB")]
    public ActionResult SaveToDB(OrderItems Client)
    {
      var errors = ModelState.Values.SelectMany(v => v.Errors);
        if (ModelState.IsValid)
        {
            if (_db == null)
                _db = new OrderDB();

            OrderItems ClientOrig = Session["Clientobj"] as OrderItems;
            ClientOrig.CLInfo = Client.CLInfo;

            Session["Clientobj"] = null;
        }

        return RedirectToAction("Index", "Home");
    }

    [Authorize]
    public ActionResult Index (OrderItems Client)
    {
        int ClientID = Convert.ToInt32(Session["Client"]);
        if ClientID == 0)
        {
            ClientID = 2;
            Session["Client"] = ClientID;
        }

        if (Session["Clientobj"] == null)
        {
            Client = new OrderItems();
            Client.CLOrderID = 123;
            Session["Clientobj"] = Client;
        }
        else
        {
            Client = Session["Clientobj"] as OrderItems
        }
        return View(Client);
    }

on post the ModelState.IsValid return false which true, but I don't have any message to tell the user where is the error to be fixed.

I tried to add : @Html.ValidationSummary(true) after the BeginForm , but it didn

Any idea please

Thanks

Upvotes: 0

Views: 96

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

You cannot use RedirectToAction if you want to retain your model state. All errors and what not are kept in the ModelState object, and when you redirect to action it's performing a new get action, which starts fresh with a clean slate.

You need to return the view like you do in the original action.

Upvotes: 1

Related Questions