Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's my solution - a <code>RemoveFor()</code> extension method on <code>ModelState</code>, modelled after MVC HTML helpers:</p> <pre><code> public static void RemoveFor&lt;TModel&gt;(this ModelStateDictionary modelState, Expression&lt;Func&lt;TModel, object&gt;&gt; expression) { string expressionText = ExpressionHelper.GetExpressionText(expression); foreach (var ms in modelState.ToArray()) { if (ms.Key.StartsWith(expressionText + ".")) { modelState.Remove(ms); } } } </code></pre> <p>Here's how it's used :</p> <pre><code>if (model.CheckoutModel.ShipToBillingAddress == true) { // COPY BILLING ADDRESS --&gt; SHIPPING ADDRESS ShoppingCart.ShippingAddress = ShoppingCart.BillingAddress; // REMOVE MODELSTATE ERRORS FOR SHIPPING ADDRESS ModelState.RemoveFor&lt;SinglePageStoreModel&gt;(x =&gt; x.CheckoutModel.ShippingAddress); } if (ModelState.IsValid) { // should get here now provided billing address is valid } </code></pre> <p>If anybody can see a way to improve it (or not have to specify the generic type argument) then please let me know. Or if this exists in MvcFutures under a different name I'd rather switch to that.</p> <p>While I'm at it here's a helper to check if ModelState is valid for a certain 'tree'</p> <pre><code> public static bool IsValidFor&lt;TModel, TProperty&gt;(this TModel model, System.Linq.Expressions.Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, ModelStateDictionary modelState) { string name = ExpressionHelper.GetExpressionText(expression); return modelState.IsValidField(name); } </code></pre> <p>Which can be used like this :</p> <pre><code> if (model.IsValidFor(x =&gt; x.CheckoutModel.BillingAddress, ModelState)) { _debugLogger.Log("Billing Address Valid", () =&gt; ShoppingCart.BillingAddress); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload