即使关闭了先前的ModelState,ModelState.IsValid()也不会验证

时间:2020-09-11 09:23:03

标签: asp.net-core model-view-controller

我正在使用一个if语句,该语句应在模型状态有效时执行一些操作,但显然ModelState.IsValid不会返回true。我尝试使用ModelState.Clear()清除以前的ModelState,但效果不佳。

这是我的控制器

// This is the first action for which I'm using the model state
    [HttpPost]
            public async Task<IActionResult> Register(userModel model)
            {
                if (ModelState.IsValid)
                {
                    userData lcl_userr = new userData
                    {
                        username = model.username,
                        password = model.password,
                        email = model.email
                    };
                    _context.users.Add(lcl_userr);
                    await _context.SaveChangesAsync();
                    ViewBag.Success = "Registered successfully";
                    ModelState.Clear();
                    return View();
                }
                return View(model); 
            }
    
// And this is the second one
            [HttpPost]
            public IActionResult Index(userModel model)
            {
                if (ModelState.IsValid)
                {
                    var findValue = _context.users.Any(o => o.username == model.username);
                    var findValue2 = _context.users.Any(o => o.password == model.password);
                    if (findValue && findValue2)
                        ViewBag.Name = "Success";
                }
                return View(model);
            }

这是表格

<form method="post" asp-action="Index" asp-controller="Portal">
            <div class="text-danger"></div>
            <div class="text-warning">@ViewBag.Name</div>
            <div class="form-group">
                <label class="mt-4 asp-for="username"">Username</label>
                <input class="form-control" type="text" required="required" asp-for="username" />
                <span></span>
            </div>

            <div class="form-group">
                <label class="mt-4" asp-for="password">Password</label>
                <input type="password" class="form-control" required="required" asp-for="password"/>
                <span></span>
            </div>

            <center>Don't have an account? <a asp-controller="Portal" asp-action="Register">Register here</a>.</center>
            <center><button value="login" class="btn btn-primary mt-3 w-25 mb-3 align-content-center">Login</button></center>
        </form>

在动作内部调用的模型类和类成员可以正常工作,并且从表单中获取的值也可以正常工作,只是模型状态不起作用。

userModel类

public class userModel
    {
        [Display(Name = "username")]
        [Required]
        public string username { get; set; }
        [Required]
        [Display(Name = "password")]
        public string password { get; set; }
        [Required]
        [Display(Name = "email")]
        public string email { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

library(shiny) library(shinyWidgets) library(DT) # ui object ui <- fluidPage( titlePanel(p("Spatial app", style = "color:#3474A7")), sidebarLayout( sidebarPanel( uiOutput("inputp1"), #Add the output for new pickers actionButton("button", "Update"), uiOutput("pickers"), numericInput("num", label = ("value"), value = 1), actionButton("button2", "Update 2") ), mainPanel( DTOutput("table") ) ) ) # server() server <- function(input, output, session) { DF1 <- reactiveValues(data=NULL) dt <- reactive({ name<-c("John","Jack","Bill") value1<-c(2,4,6) dt<-data.frame(name,value1) }) observe({ DF1$data <- dt() }) output$inputp1 <- renderUI({ pickerInput( inputId = "p1", label = "Select Column headers", choices = colnames( dt()), multiple = TRUE, options = list(`actions-box` = TRUE) ) }) observeEvent(input$p1, { #Create the new pickers output$pickers<-renderUI({ dt1 <- DF1$data div(lapply(input$p1, function(x){ if (is.numeric(dt1[[x]])) { sliderInput(inputId=x, label=x, min=min(dt1[[x]]), max=max(dt1[[x]]), value=c(min(dt1[[x]]),max(dt1[[x]]))) }else { # if (is.factor(dt1[[x]])) { selectInput( inputId = x, # The col name of selected column label = x, # The col label of selected column choices = dt1[,x], # all rows of selected column multiple = TRUE ) } })) }) }) dt2 <- eventReactive(input$button2, { req(input$num) dt <- DF1$data ## here you can provide the user input data read inside this observeEvent or recently modified data DF1$data dt$value1<-dt$value1*isolate(input$num) dt }) observe({DF1$data <- dt2()}) output_table <- reactive({ req(input$p1, sapply(input$p1, function(x) input[[x]])) dt_part <- dt2() for (colname in input$p1) { if (is.factor(dt_part[[colname]]) && !is.null(input[[colname]])) { dt_part <- subset(dt_part, dt_part[[colname]] %in% input[[colname]]) } else { if (!is.null(input[[colname]][[1]])) { dt_part <- subset(dt_part, (dt_part[[colname]] >= input[[colname]][[1]]) & dt_part[[colname]] <= input[[colname]][[2]]) } } } dt_part }) output$table<-renderDT({ if (input$button | input$button2) { DF1$data }else return(NULL) }) } # shinyApp() shinyApp(ui = ui, server = server) 的第二个请求,该请求的模型不包含public IActionResult Index(userModel model)email是错误的。

IsValid

电子邮件地址的 [Required] [Display(Name = "email")] public string email { get; set; } 实例在“错误”集合中有错误。

enter image description here

MVC为提交的属性创建模型状态时,还会遍历ModelState中的每个属性,并使用与其关联的属性来验证属性。如果发现任何错误,则会将它们添加到属性ViewModel的“错误”集合中。

解决方案

只需在ModelState动作中删除if (ModelState.IsValid),就根本不需要添加它。



如果您坚持保留Index,则需要在if (ModelState.IsValid)内添加email

form
相关问题