0

I have a question about ModelState.AddModelError method and about the ValidationMessage method.

I am new to ASP.NET MVC and I am a little confused.

I wrote this code:

public ActionResult update(FormCollection collection)
{
    int oos = 0;

    try
    {
        oos = int.Parse(collection[0]);
    }
    catch
    {         
    }

    data d = new data();

    TryUpdateModel(d , collection.ToValueProvider());

    if (ModelState.IsValid)
    { 
         return View("index",d);
    }
    else
    {      
        ModelState.AddModelError("Date", "Wronge Date");   
        d.Id = 50;
        return View("index",d);
    }
}

and this code in the view side

@{

    ViewBag.Title = "index";
}

<h2>index</h2>
@TempData["Hi"]

@Html.ValidationMessage("fullname") 

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() @Html.TextBox("id", 70) 
    @Html.TextBox("Date", "3/2/1991 12:00:00 ص")
    @Html.ValidationMessage("Date","Please insert the correct Date Format") 

    <input type="submit"> 
}

My questions are, why the message Please insert the correct Date Format appears directly when I rune the index while still I did not submit the form, why when I submit the form with error in the date format,the same message appear but not the message that I set to the Date Key in the update method which is Wronge Date.

maybe still I do not understand those two methods so I hope to find somebody to explain them to me.

explnation with example or reference would be appreciated

2
  • 1
    Have you even declared the model in your view (@model yourAssembly.data)? Why are you using FormCollection instead of posting your model? And use the strongly typed helpers - @Html.TextBoxFor(m -> m.Date) and @Html.ValidationMessageFor(m -> m.Date) Commented Apr 19, 2015 at 23:06
  • If you post the model that will more helpful for us to know what kind of Message or validation you have set to your Date key!! Commented Apr 20, 2015 at 5:19

1 Answer 1

2

Please look at http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation

Because you have already entered a message in the View it will use that over your error that you are adding from the controller. As for your fullname you do not have a message set yet, only the placehoder for the field.

Sign up to request clarification or add additional context in comments.

Comments

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.