I have a ASP.NET MVC 3 view with esentially two forms, but which reside in the same form tag.
Not sure if this is the correct way to approach this, so please suggest if theres a better solution.
The user have two options on this single page. It’s about subscribing to a newsletter, and if the user already has a subscription number, only one of the “forms” are required to be validated.
If the user does not have a subscription number, the other form is required to be validated.
I’m aware that this could be developed much more user friendly (and programmer), but it’s a requirement from the customer.
My problem is, when submitting the form, all of the fields are of course validated. Somewhere I need to provide a check to see if the user has filled out the SubscriptionNumber field, and then control what “form” to validate.
Do you have any suggestions on how to do that? I would of course like to keep this as simple as possible.
Here’s my view Subscribe:
@model SubscribeNewsletterModel
@using (Html.BeginForm())
{
@Html.EditorFor(m => m.ExistingSubscriber)
@Html.EditorFor(m => m.NewSubscription)
@Html.ValidationSummary()
<input type="submit" />
}
My view model for this view, looks like this:
public class SubscribeNewsletterModel
{
public SubscribeNewsletterModel(SubscriptionModel subscriptionModel,
ExistingSubscriberModel existingSubscriberModel)
{
this.NewSubscription = subscriptionModel;
this.ExistingSubscriber = existingSubscriberModel;
}
// The models contains validation logic (attributes like Required, etc.)
public SubscriptionModel NewSubscription { get; set; }
public ExistingSubscriberModel ExistingSubscriber { get; set; }
}
And my controller responsible for handling the POST request. This doesn’t do anything yet – just for validation:
[HttpPost]
public ActionResult Subscribe(
[Bind(Prefix="NewSubscription")] SubscriptionModel newSubscriptionModel,
[Bind(Prefix="ExistingSubscriber")] ExistingSubscriberModel existingSubscriberModel)
{
var vm = new SubscribeNewsletterModel(newSubscriptionModel, existingSubscriberModel);
return View(vm);
}
Based on your condition: “It’s about subscribing to a newsletter, and if the user already has a subscription number, only one of the “forms” are required to be validated. If the user does not have a subscription number, the other form is required to be validated.”
Create parameter in your view that will be send back to controller where you validate your form and use this parameter to determine what will be validated. You will have to work with
You can remove properties that you dont want to be validated by key.