tags:

views:

128

answers:

3

I have a website that uses one Action method which passes a pagename to the get action method. In the action method it finds the model item by the pagename and returns the relevant stuff to the view.

I have now created a POST action method for this because I need it in my contact page. I still need to find the model by page name and return it to the view however when the user submits the contact information I do a TryUpdateModel on my Enquiry model item and if not valid it returns the errors into the modelstate and the validation summary shows the errors but none of the information they submitted is re-rendered.

Is there anyway I can return the page model and get the textboxes to re-render what they had previously typed when the model fails?

A: 

If you add a property to your view model for what should be bound to the textbox (in my example Thing) you could use something like:

<%=Html.TextBox("Thing", Model.Thing != null ? Model.Thing : string.Empty)

Kindness,

Dan

Daniel Elliott
I was trying to avoid having a View model seperate from my DB model but am thinking thats the only approach available
Jon
I think you are right; you are going to need a view model in this case. Kindness, Dan
Daniel Elliott
A: 

Here's what we do (with stuff not essential to this question removed):

private ModelType UpdateModel(Guid id)
{
    var dbData = (from m in Repository.SelectAll()
                  where m.Id == id
                  select new ModelType
                  {
                      Id = m.Id,
                      Data = m.Data
                  }).First();
    return UpdateModel(dbData);
}

private ModelType UpdateModel(ModelType model)
{
    //add other data for view:
    model.SelectStuff = new SelectList( //...
    // etc.
    return model;
}

[HttpGet]
public ActionResult Update(Guid id)
{
    return View(UpdateModel(id));
}

[HttpPost]
public ActionResult Update(ModelType model)
{
    if (!ModelState.IsValid)
    {
        return View(UpdateModel(model));
    }
    // else post to repository
}
Craig Stuntz
A: 

I worked out I could use the following approach:

<input name="ENQ.Name" class="inputText" type="text" maxlength="150" title="Please enter your name" value="<%= ViewData.ModelState["ENQ.Name"] != null ? ViewData.ModelState["ENQ.Name"].Value.AttemptedValue : "" %>" />
Jon