Michael Chiche
Michael Chiche

Reputation: 191

Using modelstate.isvalid to validate data from inside the controller in MVC3

I am pretty new to ASP.NET MVC3 but i have about 4 years of experience with PHP frameworks.

I am trying to build an MVC3 web app, but i am having issues with validationg my model. Here is a test controller to show you what i am trying without success to do.

I am trying to pass a value to my model inside the controller, but it doesnt take it into account the parameter.

I tried using modelstate.setmodelvalue, for junk.sentence, but it keeps the value from the POST request which is invalid an that i want to change by default (for test purposes) in the controller.

Can anyone help?

Thanks in advance.

Michael

    [HttpPost]
    public ActionResult Create(Junk junk)
    {
        //ModelState.Clear();
        junk.sentence = "coucou";

        ModelState.SetModelValue("sentence", new ValueProviderResult(junk.sentence, junk.number, null));


        //ModelState
        if (ModelState.IsValid)
        {
            db.Junks.Add(junk);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        return View(junk);
    }

    //
    // GET: /Junk/Edit/5

    public ActionResult Edit(int id)
    {
        Junk junk = db.Junks.Find(id);
        return View(junk);
    }

Upvotes: 1

Views: 1445

Answers (2)

Matt Esch
Matt Esch

Reputation: 22966

ModelState.IsValid returns false when there are model errors added to the model state. MVC validates the properties on your model and creates a list of errors for you in the ModelState. You must remove the errors from the model state that you wish to be ignored from inside your controller action. You can then update the actual values on the model. (Darin Dimitrov shows you an example of doing this)

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

Try removing it from modelstate:

[HttpPost]
public ActionResult Create(Junk junk)
{
    junk.sentence = "coucou";

    //ModelState
    if (ModelState.IsValid)
    {
        db.Junks.Add(junk);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }

    ModelState.Remove("sentence");
    return View(junk);
}

This assumes that in your view you have a corresponding input field that was generated using some of the Html helpers such as EditorFor for example:

@Html.EditorFor(x => x.sentence)

or:

@Html.TextBoxFor(x => x.sentence)

Upvotes: 1

Related Questions