开发者

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

开发者 https://www.devze.com 2022-12-12 11:57 出处:网络
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 st

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?


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
}


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号