Question

I have a question for you guys. I am programming an application where I can create exercises with multiple answers. I asked something a few days ago and it completely works at this moment.

Asp.net MVC with Entity, using jquery to pass data into List. Does not work

The source is not the same anymore. I only have one question about modelstate.isvalid.

Let me give you guys an example. I have an ExerciseModel with a list Answers. Creating new answers on the fly with jQuery and EditorTemplates works perfect. The only thing is that validation will never work now. I want to add modelstate.isvalid into my httpPost method for validation.

The question is about Editing/creating new answers

public ActionResult EditQuestion(int id)
{
    ExerciseModel exercisemodel = db.Exercise.Find(id);
    if (exercisemodel == null)
    {
        return HttpNotFound();
    }
    exercisemodel.Answers = GetAnswers(id);
    ViewBag.CourseId = new SelectList(db.Course, "CourseId", "CourseName", 
                                 exercisemodel.CourseId);
    return View(exercisemodel);
}


[HttpPost]
public ActionResult EditQuestion(ExerciseModel exercisemodel)
{
    foreach (var answer in exercisemodel.Answers)
    {
        db.Entry(answer).State = answer.AnswerId == 0 ?
                        EntityState.Added :
                        EntityState.Modified;
    }
    db.SaveChanges();
    return RedirectToAction("Index");
}

The reason for this, is because I can create new answers while I also can edit the existing answers and add them into my list of answers in my ExerciseModel. So my ExerciseModel changes when i create new answers. That's the reason why modelstate.isvalid never will be true.

How can I get this to work?

Was it helpful?

Solution

Got it ! Thanks guys for your replies. Strange but it works.. I already had a hidden Id. I have a partial with just few table rows. This, for adding new answers into my existing page with jQuery.

I had;

    <input type="hidden" id="Answers_@(Model.AnswerId)__Id" class="iHidden"  name='Answers[@Model.AnswerId].AnswerId' />

Because it creates a new row with an answer. Now I replaced it with.

    @Html.HiddenFor(x=>x.AnswerId, new { @class = "iHidden" })

And it works now. Don't know why but well, razor does the job.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top