NemanjaT NemanjaT - 2 months ago 15
ASP.NET (C#) Question

ASP.NET form submit part of a model

This is just something that has been puzzling me, I'm wondering if there's a built in way for this.

Say you have a

Package
class

public class Package
{
public A AObject { get; set; }
public B BObject { get; set; }
}


And you have a view that uses this
Package
.

public ActionResult Action()
{
return View(new Package());
}


Now the view will accept this model and have 2 forms.

@model Path.To.Package

@Html.BeginForm("SubmitA", "MyController")
{
@Html.TextBoxFor(m => m.AObject.SomeProperty);
<input type="submit" />
}
@Html.BeginForm("SubmitB", "MyController")
{
@Html.TextBoxFor(m => m.BObject.AnotherProperty);
<input type="submit" />
}


If one would create two actions needed above that take
Package
as argument, this would work without question...

public JsonResult SubmitA(Package items) { ... }
public JsonResult SubmitB(Package items) { ... }


But at
SubmitA
the BObject would be null and in
SubmitB
AObject would be null.

My question here is whether you can submit only a part of the model? So the first form would only submit
AObject
and the second
BObject
so you could actually reach these via the following actions:

public JsonResult SubmitA (A a) { ... }
public JsonResult SubmitB (B b) { ... }

Answer

You can use the Prefix property of BindAttribute to bind to complex properties of a model. The attribute effectively removes the prefix from the submitted name/value pairs when binding to model.

Your controller methods would be

public JsonResult SubmitA([Bind(Prefix = "AObject")]A model) { ... }
public JsonResult SubmitB([Bind(Prefix = "BObject")]B model) { ... }
Comments