Rob
Rob

Reputation: 10248

ASP MVC 3 bind model of different class type

Assuming I have two classes (Product & ProductSearch) with the same Property "Title"

If I have a field in my form:

<input type="textbox" name="Product.Title" id="Product_Title"/>

I can bind it in the controller using:

public ActionResult Search(Product product)

But is there any way I can specify a bind argument so that it binds to:

public ActionResult Search(ProductSearch productSearch)

I tried [Bind(Prefix = "Product")] to no avail.

Upvotes: 1

Views: 400

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

The [Bind(Prefix = "Product")] should work. Example:

Model:

public class ProductSearch
{
    public string Title { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index([Bind(Prefix = "Product")]ProductSearch productSearch)
    {
        return Content(productSearch.Title);
    }
}

View:

@using (Html.BeginForm())
{
    <input type="text" name="Product.Title" id="Product_Title" />
    <button type="submit">OK</button>
}

Upvotes: 1

Related Questions