开发者

Bind part of ViewModel

I have the following ViewModel

public class NewCustomerViewModel {
    public long CustomerId {get;set;}
    public NewCustomerFormViewModel NewCustomerForm {get;set; }
}

NewCustomerFormViewModel contains only fields which are part of the form. And only them I would like to validate. So I would like to have the following Action signature:

[HttpPost] 
publ开发者_如何学JAVAic ActionResult NewCustomer(long battleId,
    NewCustomerFormViewModel newCustomerFormViewModel)

Unfortunately it doesn't work with default ModelBinder. So what is the easiest way to bind properties of NewCustomerViewModel to NewCustomerFormViewModel?

Update. Here is the part of my view:

Title @Html.TextBoxFor(m => m.NewCustomerForm.Title, Model.NewCustomerForm.Title)

So ModelBinder looks for NewCustomerForm property which he can't find in NewCustomerForViewModel


ASP.NET MVC relies heavily upon naming conventions for resolving Views, Actions, Controllers, and even parameters. The parameters are probably being posted under a NewCustomerForm namespace (e.g. NewCustomerForm.Name=John), because that's how they fit into the model that you're producing inputs for. Try renaming your parameter to newCustomerForm so that the binder actually does find an object by that name.

[HttpPost] 
public ActionResult NewCustomer(long battleId,
    NewCustomerFormViewModel newCustomerForm)


Maybe i am not 100% sure about your requirements as you didn't provided your controller code and view code. But as I have understood that you want a mechanism to include the 'NewCustomerForm' under validation and binding and exclude 'CustomerId' out.

It this is the case then try the following code.

Code for Model

Exclude the properties you don't want to bind.

[Bind(Exclude = "CustomerId")]
public class NewCustomerViewModel
{
    public long CustomerId { get; set; }
    public NewCustomerFormViewModel NewCustomerForm { get; set; }
}

public class NewCustomerFormViewModel
{
    public string Name { get; set; }
    public string Title { get; set; }
}

Code for Controller

public class TestController : Controller
{       
    public ActionResult Index(string username )
    {
        NewCustomerViewModel model = new NewCustomerViewModel();
        model.NewCustomerForm = new NewCustomerFormViewModel();
        return View(model);
    }
    [HttpPost]
    public ActionResult IndexPost(NewCustomerViewModel m)
    {   
        UpdateModel(m);
        return View("index",m);
    }
}

Code for View

<h2>Index</h2>

<% using (Html.BeginForm("indexpost","test")) {%>
<%: Html.TextBoxFor(m => m.CustomerId, Model.CustomerId)%>
<%: Html.TextBoxFor(m => m.NewCustomerForm.Title, Model.NewCustomerForm.Title)%>
<%: Html.TextBoxFor(m => m.NewCustomerForm.Name, Model.NewCustomerForm.Name)%>  

<input type="Submit" value="submit" />
<%} %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜