views:

213

answers:

1

As we all know RenderAction() is either part of:

  • Asp.net MVC 1 Futures or
  • Asp.net MVC 2 Beta 2

and allows us to render action result inside another view or partial view.

Description

  1. You have a view with multiple partial views displayed using RenderAction() helper.
  2. At least two partial views render a <form> probably by using Html.BeginForm() that postback to original view.
  3. Postback is not performed via Ajax call
  4. Postback data is validated upon form POST.

Problem

When one of the forms gets posted back the other one renders as invalid.

Has anyone used this pattern and solved it? We should somehow know which form performed postback and only that one should validate its POST data. Others should either ignore validation or perform regular HttpVerb.Get action processing.

+1  A: 

Have a hidden field in the form to indicate which one. Or, have a prefix passed to the partial and appended to each element in the form.

About prefixes. First way is to have two properties, calling Html.RenderPartial("partial", Model.Data1/2.WithPrefix("data1")).

public class FormModel
{
   public string Prefix { get; set; }
}

public class FormData
{
   public FormModel Data1 { get; set; }
   public FormModel Data2 { get; set; }
}

public ActionResult HandlePost(FormData data)
{
   if (data.Data1 != null) {} else {}
}

Second way is the same but use two action parameters.

public ActionResult HandlePost(FormModel data1, FormModel data2)
{
   if (data1 != null) {} else {}
}

In the partial view you do

<%= Html.TextBox(Model.Prefix + ".FormModelField", Model.FormModelField) %>

that is, you set field name with the prefix passed in the model.

Of course you may vary this in details.

queen3
I understand the first part about having a hidden field, but I don't understand the second suggestion. Append to element IDs or where? Can you rephrase it please?
Robert Koritnik
adding prefixes could possibly mean I have to create my own model binder that would recognise my fields and bind them to action parameters as expected?
Robert Koritnik
Anyway. I did go the *hidden field* route. It doesn't change my URLs and I could make it as transparent as possible. I've written another extension method `BeginSubForm()` that renders an additional hidden field at the beginning that identifies a particular form that does postbacks.
Robert Koritnik