简体   繁体   中英

Model.Isvalid getting failed in my MVC 4 application. How do fix this?

I have one view and that view contains create user and log in forms. For both i have different models. When user clicks on Register button i will pass register model values and for log in click i pass log in model values.I have added some validation in model also (You can see it my code below). Since i have two model i have added one more model(Account) which holds both this model.Am passing this model(Account) from view to controller on click of register or log in. The reason why Model is invalid all the time is, when user clicks on log in button am passing account model which has both Register and log in model but with only log in details .All the values for register model will be null since user clicked on log in (Only log in data will be there). So in controller Model.Is valid is always false since no values are there for register model.

So is there any other way to validate a particular model ? What is the solution in this case?

 @model Selfie.Models.Account
   @using (Html.BeginForm())     
        { 

                   @Html.TextBoxFor( model => model.RegisterModel.FirstName,null, new {@class="form-control",id="fn", placeholder=" First Name",required="true",maxlength="20"})
                   @Html.ValidationMessageFor(model => model.RegisterModel.FirstName) 

                    @Html.TextBoxFor(model => model.RegisterModel.LastName,null, new { @class = "form-control",id="ln", placeholder=" Last Name",required="true",maxlength="20"})
                    @Html.ValidationMessageFor(model => model.RegisterModel.LastName)

                   <button type="submit" class="btn btn-success" id="btnsub">Create Account</button>        


        } 
//Login
@using (Html.BeginForm("Login", "Selfie", FormMethod.Post, new { }))
        {   


                    @Html.TextBoxFor(model => model.LoginModel.UserName,null, new { @class = "form-control",id="lem"})
                    @Html.ValidationMessageFor(model => model.LoginModel.UserName) 

                     @Html.TextBoxFor(model => model.LoginModel.Pwd,null, new { @class = "form-control"})
                     @Html.ValidationMessageFor(model => model.LoginModel.Pwd) 

                    <button type="submit" class="btn btn-success" id="btnlogin">Log In</button>

        }    

//Controller

[HttpPost]

    public ActionResult Register(Account registration)
    {
        if(Model.Isvalid)
          {
              string a= Account.fname; 

            }
    }

    [HttpPost]
    public ActionResult Login(Accountlogin)
    {

        if(Model.Isvalid)
          {
              string a= Account.username; 

            }
    }

Model

   [Required(ErrorMessage="Last name is required")]
    public string LastName {get; set;}
    [Required(ErrorMessage="First name is required")]
    public string FirstName { get; set; }

}

public class LoginModel
{
    [Required(ErrorMessage = "User name is required")]
    [Display(Name = "User name")]
    [RegularExpression("^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$", ErrorMessage = "Invalid email")]
    public string UserName { get; set; }

    [Required(ErrorMessage = "Password is required")]
    public string Pwd { get; set; }
}
public class Account
    {
        public LoginModel LoginModel{get; set;}
        public RegistrationModel RegisterModel {get; set;}
    }

Well, first things first as Stephen mentioned in comments, these two shouldn't really reside on the same form.

However , I have came across the same problem in the past in regards to validating only parts of the model (in situations where your models and entities implement the same interface sometimes it may not be practical to validate everything).

I got round this by doing the following, you only validate the fields that are passed in from the form. So in your actions, you'd do:

var itemsToIgnore = ModelState.Keys
    .Where(c => !Request.Form.AllKeys.Contains(c))
    .ToList();

foreach (var item in itemsToIgnore)
{
    ModelState.Remove(item);
}

if (ModelState.IsValid)
{
    //all fields passed in were valid
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM