简体   繁体   中英

ASP.Net MVC - Merge model and formcollection into object to pass to a View

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?

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

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
}

我计算出可以使用以下方法:

<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 : "" %>" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM