开发者

Form for a different model than the view page in ASP.NET MVC 3

I have Results page that contains an signup form开发者_如何转开发. I'm trying to use client-side validation on the email model, but I can't because the model type is different than the type I'm posting.

class Results
{
     ... // some results data to display
}

class EmailSignup
{
    public virtual int Id { get; set; }

    [Required(ErrorMessage = "Please enter your email.")]
    [DataType(DataType.EmailAddress)]
    [RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ErrorMessage = "Please enter a valid email address.")]
    public virtual string Email { get; set; }
}

Results.cshtml

@model MyApp.Results
[display results]
...
@using (Html.BeginForm("SubmitEmail", "AnalysisResults", FormMethod.Post))
{
     <fieldset>
     @Html.TextBoxFor( model => model.???? )
     </fieldset>
}

The type I want the user to submit is EmailSignup, not Results.


Move the form to a partial view that takes an EmailSignup model.


This can be done quite easily. You just have to do it like this:

var contactModel = new ContactModel();
@Html.TextBoxFor(m => contactModel.Title)
@Html.ValidationMessageFor(m => contactModel.Title)

The validation works like a charm.


I have find out 2 more ways

  1. Override the Name attribute for TextBoxFor and set it as the property name.
    var formModel = new ForgotPasswordFormModel();
    @Html.TextBoxFor(m => formModel.UsernameOrEmail, new { Name = "UsernameOrEmail" })
  1. Specify the same exact model name as the post method parameter.
    var formModel = new ForgotPasswordFormModel();
    @using (Html.BeginForm("ChangePassword", "LoginSurface")
    {
       @Html.TextBoxFor(m => formModel.UsernameOrEmail)
    }
    ...
    public virtual ActionResult ChangePassword(ForgotPasswordFormModel formModel)


You could create another HtmlHelper like this

var emailSignupHtml = new HtmlHelper<EmailSignup>(Html.ViewContext, new ViewDataContainer<EmailSignup>(new EmailSignup()));

and use it like this

@emailSignupHtml.TextBoxFor(m => m.Email)

For the ViewDataContainer I use following helper class

public class ViewDataContainer<TModel> : ViewDataDictionary<TModel>, IViewDataContainer
{
   public ViewDataContainer(TModel model) : base (model)
   {
      ViewData = new ViewDataDictionary(model);
   }

   public ViewDataDictionary ViewData { get; set; }
}


I guess you can also try @HTML.Action("EmaialSignup") and your controller will have a Function calling the partial view if you have to render multiple model bounded View in this view

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜