views:

1797

answers:

2

I am trying to generate such HTML

    <form action="/some/process" method="post">
        <input type="hidden" name="foo.a" value="aaa"/>
        <input type="hidden" name="bar.b" value="bbb"/>
        <input type="submit" />
    </form>

so it can be processed by this Action:

    public ActionResult Process(Foo foo, Bar bar)
    {
        ...
    }

Given the Action code

    public ActionResult Edit()
    {
        ViewData["foo"] = new Foo { A = "aaa" };
        ViewData["bar"] = new Bar { B = "bbb" };

        return View();
    }

what should I write in Edit.aspx view? I don't want to write names 'foo.a' and 'bar.b' manually.

+6  A: 

String-indexed ViewData is bad. What you probably want to do is make a little wrapper class for your multi-variable view data and pass that to a strongly typed view. IE:

public class FooBarViewData
{
   public Foo Foo {get; set;}
   public Bar Bar {get; set;}
}
public ActionResultEdit()
{
   FooBarViewData fbvd = new FooBarViewData();
   fbvd.Foo = new Foo(){ A = "aaa"};
   fbvd.Bar = new Bar(){ B = "bbb"};
   return View(fbvd);
}

Then your view is just strongly typed to FooBarViewData and you can call members of that object using the Model property.

Wyatt Barnett
+4  A: 

You have a couple of choices. First, you can reference them from ViewData and use an HtmlHelper extension. Or you could create a view-specific model and use a strongly-typed viewpage for Edit.aspx.

public class EditModel
{
    public Foo foo { get; set; }
    public Bar bar { get; set; }
}

public ActionResult Edit()
{
    var model = new EditModel();

    model.foo = new Foo { A = "aaa" };
    model.bar = new Bar { B = "bbb" };

    return View( model );
}

(Edit.aspx is of type ViewPage<EditModel>)

Either way, the HtmlHelper extension will pick up any initial values.

<form action="/some/process" method="post">
     <%= Html.Hidden( "foo.A" ) %>
     <%= Html.Hidden( "bar.B" ) %>
</form>
tvanfosson