gpt4 book ai didi

asp.net - MVC 多按钮验证

转载 作者:行者123 更新时间:2023-12-02 02:01:39 25 4
gpt4 key购买 nike

我在表单上有 4 个按钮,“提交 1”调用 Controller A,“提交 2”调用 Controller B。

我在同一个表单上还有“按钮 1”和“按钮 2”,我不希望对它们进行验证/触发。

如何让“提交 1”和“提交 2”来验证表单而不是“按钮 1”和“按钮 2”?

同时“按钮 1”和“按钮 2”应该提交给不同的 Controller 。我如何实现这一目标?

public class SampleForm
{
[Display(Name = "FName: ")]
[Required(ErrorMessage = "Enter FName")]
public string FirstName { get; set; }

[Display(Name = "LName: ")]
[Required(ErrorMessage = "Enter LName")]
public string LastName { get; set; }

[Display(Name = "Bypassid: ")]
[Required(ErrorMessage = "Enter Bypassid")]
public string Bypassid { get; set; }
}

@model SampleForm
@using (Html.BeginForm("SampleForm", "SampleController", FormMethod.Post, new { name = "frmSample", id = "frmSample" }))
{
@Html.LabelFor(model => model.FirstName)
@Html.TextBoxFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)

@Html.LabelFor(model => model.LastName)
@Html.TextBoxFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)

@Html.LabelFor(model => model.Bypassid)
@Html.TextBoxFor(model => model.Bypassid)
@Html.ValidationMessageFor(model => model.Bypassid)

<input type="submit" value="Submit 1" name="Command" />

<input type="submit" value="Submit 2" name="Command" />

<button type="button" name="Button 1" value="Button 1">Button 1</button>

<button type="button" name="Button 2" value="Button 2">Button 2</button>
}

我希望“提交 1”和“提交 2”使用 DataAnnotations 验证表单,但是当我单击“按钮 1”时,我想确保“Bypassid”字段中有值并重定向到另一个 Controller (比如 .当我点击“按钮 2”时,我不会验证任何内容,只是重定向到另一个 Controller 。

最佳答案

关于提交到两个操作,您有两个提交按钮和独立值的正确想法。您可以使用操作中的值来解读您希望如何处理请求。尽管您在一天结束时只会提交一个操作,但您可以在操作中重定向它以处理流程的差异。例如

@using (Html.BeginForm("BasicAction"))
{
@* controls *@
<input type="submit" value="action1" name="command" />
<input type="submit" value="action2" name="command" />
}

然后,你的 Controller :

[HttpPost]
public ActionResult BasicAction(MyModel model, String command)
{
if (ModelState.IsValid)
{
switch (command)
{
case "action1":
return RedirectToAction("Action1", new { model = model });
case "action2":
return RedirectToAction("Action2", new { model = model });
}
}
return View(model);
}

// handle action1
[NonAction]
public ActionResult Action1(MyModel model)
{
// do whatever
}

[NonAction]
// handle action2
public ActionResult Action2(MyModel model)
{
// do whatever
}

就禁用验证而言,您可以在按钮 1 和 2 上设置 disableValidation=true,客户端验证将被忽略(我相信这是从 MVC2 开始的)。为此,在定义这些按钮后添加以下 javascript:

<script>
// IDs of the buttons to be disabled
var disabled = ['button1','button2'];
for (var i = 0; i < disabled.length; i++){
document.getElementById(disabled[i]).disableValidation = true;
}
</script>

关于asp.net - MVC 多按钮验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16975611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com