Sunday, 15 March 2015

c# - Validation for ViewModels different from the page ViewModel -



c# - Validation for ViewModels different from the page ViewModel -

assume have page (view) takes viewmodel:

@model ienumerable<myproject.viewmodels.myviewmodel>

in page, have form posts info through viewmodel (let's phone call postmodel):

@using (html.beginform("order", "order", formmethod.post, new { @class = "form-horizontal", role = "form" })) { @html.antiforgerytoken() <h4>give order info</h4> <hr /> @html.validationsummary() <div class="form-group"> <label for="order.name" class="col-md-2 control-label">name:</label> <div class="col-md-10"> @html.textbox("order.name", null, new { @class = "form-control" }) @html.validationmessage("order.name") </div> </div> ... }

this processed on controller in order httppost action method takes argument of postmodel's type.

i can display validation messages in style have above. question is, how (if possible) can create typed postmodel? like:

@html.textbox<mypostmodel>(t => t.order.name, ...) @html.validationmessagefor<mypostmodel>(t => t.order.name)

is @ possible, without changing viewmodel of page?

you can utilize different partial-view form , in partial-view can specify of type want, in case, see in code example, order

lets have model called order next definition

public class order { public string name { get; set; } }

and partial-view called _mypostpartialview.cshtml definition

@model order @using (html.beginform("order", "order", formmethod.post, new { @class = "form-horizontal", role = "form" })) { @html.antiforgerytoken() <h4>give order info</h4> <hr /> @html.validationsummary() <div class="form-group"> @html.label(m => m.name, "name:") <div class="col-md-10"> @html.textbox(m => m.name, null, new { @class = "form-control" }) @html.validationmessage(m => m.name) </div> </div> ... }

and you're done!

c# asp.net-mvc validation asp.net-mvc-5

No comments:

Post a Comment