1

I have a view for processing a credit card transaction. It uses a simple model containing a CreditCardNumber property. If there are errors I blank out the CreditCardNumber property on the model. The problem is that MVC goes ahead and fills in the CreditCardNumber. I am guessing it is looking at the posted form values and is trying to helpfully fill it back in for me. I don't want this.

How can I make MVC's Html.EditorFor not use the posted form values and use my model's property value exclusively?

2
  • What does your controller return on a failed request? Commented Oct 17, 2011 at 23:39
  • An otherwise fully populate model Commented Oct 17, 2011 at 23:40

2 Answers 2

1

It should work correctly if you explicitly pass the edited model to the View call.

public ActionResult BuyNow(BuyNowViewModel vm)
{
  if (!ModelState.IsValid)
  {
      vm.CreditCardNumber = null;
      return View(vm);
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

But you'll only want to do this if !ModelState.IsValid right?
Right. Or some other non-standard validation code fails somewhere (one never knows, thanks for the suggestion).
This is exactly what I am already doing. The model does not contain the CreditCardNumber when its passed to the view
You might need to post some code in order to troubleshoot this issue, because what you're describing isn't normal.
0

Your View is checking your ModelState first, then your ViewModel. So if you manually change values, you need to clear your ModelState.

ModelState.Clear();

Useful blog on the subject: http://balawinwin.wordpress.com/2012/11/24/asp-net-mvcs-html-helpers-ignoring-model-changes/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.