NemanjaT NemanjaT - 11 months ago 57
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


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

And you have a view that uses this

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
as argument, this would work without question...

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

But at
the BObject would be null and in
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
and the second
so you could actually reach these via the following actions:

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

Answer Source

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) { ... }