javascript - 将选定的下拉菜单与条件进行比较

标签 javascript c# asp.net asp.net-mvc

我正在创建一个可以根据 MVC 中的条件进行访问的表单。我首先使用下拉列表和提交按钮进行查看,我希望当单击提交按钮时,传递下拉列表中的值并将其与为该值设置的条件进行比较,如果条件不正确,它会显示警报而不是处理表格。

这是我的代码:

public ActionResult ChooseType()
{
    var x = DataAccess.GetEmployee(@User.Identity.Name);

    var lists = new SelectList(RuleAccess.GetAllRule(), "ID", "TypeDetail");
    ViewBag.CategoryId = lists;

    /*rule*/
    ViewBag.comp1 = Logic.AnnualToogle(@User.Identity.Name);

    if (x.EmpSex == "F" && x.EmpMaritalSt == "NIKAH")
    { ViewBag.comp2 = 1; }
    else ViewBag.comp2 = 0;

    return View();
}


[HttpGet]
public ActionResult Create(int lv_type)
{

    var type = RuleAccess.GetTypeByID(lv_type);
    ViewBag.type = type;
    var model = new LeaveApplicationViewModels();
    model.X = DataAccess.GetEmployee(@User.Identity.Name);
    model.C = DataAccess.GetLeaveApp(@User.Identity.Name);

    /*disable*/
    ViewBag.dis = DataAccess.GetDisabledDate(@User.Identity.Name); 

    /*max*/
    var max= RuleAccess.GetMaxByID(lv_type);
    ViewBag.c = max;
    if (lv_type == 1)
    {
        var used = RuleAccess.CountUsedAnnual(@User.Identity.Name);
        var rem = max - used;
        ViewBag.a = used;
        ViewBag.b = rem;
    }
    else 
    {
        ViewBag.b = max;
    }
    return View(model);
}

在我看来,我使用了 Viewbag.comp 1 和 2:

<script type="text/javascript">

var x = @ViewBag.comp1;
var y = @ViewBag.comp2;

function validatecreate()
{
   var value= document.getElementById("lv_type").value;

    if (value==1)
    {
        if(x==1)
            document.getElementById('validatecreate').submit();
        else { alert('Action cant be done. You either have another annual leave application in pending status or you have reach the limit of annual leave'); }
    }
    else if(value==2)
    {
        if(y==1)
            document.getElementById('validatecreate').submit();
        else { alert('Action cant be done. You either are Male or Not Married Yet'); }
    }
    else if(value==3)
    {
        document.getElementById('validatecreate').submit();

    }

    else { 
        document.getElementById('validatecreate').submit();
        //alert('Http Not Found'); 
    }
}

@Html.DropDownList(
    "lv_type", (SelectList) ViewBag.CategoryId, 
    "--Select One--", 
    new{ //anonymous type
        @class = "form-control input-sm"
    }
) 

我觉得我做错了,特别是因为如果有人手动输入 ?lv_type=2 的网址,他们不会验证并可以直接转到表单。但我需要 lv_type bcs 的值,我认为我使用它。请帮忙:(

最佳答案

验证必须始终在服务器上完成,而客户端验证只能被视为一个很好的好处,可以最大限度地减少对服务器调用的需要。在下拉列表中向用户呈现选项,然后告诉他们无法选择该选项,这是一种糟糕的用户体验。相反,您应该仅显示适用于用户的选项(并删除您显示的所有脚本)。

在您的 RuleAccess 类中创建一个附加方法,例如 GetEmployeeRules(Employee employee),它仅返回适用于该员工的规则,例如

public static List<Rule> GetEmployeeRules(Employee employee)
{
    // Get the list of all rules
    if (employee.EmpSex == "F" && employee.EmpMaritalSt == "NIKAH")
    {
        // Remove the appropriate Rule from the list
    }
    .....
    // Return the filtered list
}

此外,您应该在 View 中使用 View 模型

public class LeaveTypeVM
{
    [Required(ErrorMessage = "Please select a leave type")]
    public int SelectedLeaveType { get; set; }
    public IEnumerable<SelectListItem> LeaveTypeList { get; set; }
}

然后在ChooseType()方法中

public ActionResult ChooseType()
{
    var employee = DataAccess.GetEmployee(@User.Identity.Name);
    var rules = RuleAccess.GetEmployeeRules(employee);
    var model = new LeaveTypeVM()
    {
        LeaveTypeList = new SelectList(rules, "ID", "TypeDetail")
    };
    return View(model);
}

并在 View 中

@model LeaveTypeVM
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.SelectedLeaveType, Model.LeaveTypeList, "--Select One--", new { @class = "form-control input-sm" }
    @Html.ValidationMessageFor(m => m.SelectedLeaveType)
    <input type="submit" value="Submit" />
}

并提交到 POST 方法,该方法允许您轻松返回无效的 View ,或重定向到 Create 方法。

[HttpPost]
public ActionResult ChooseType(LeaveTypeVM model)
{
    if (!ModelState.IsValid)
    {
        model.LeaveTypeList = .... // as per GET method
    }
    return RedirectToAction("Create", new { leaveType = model.SelectedLeaveType });

以及在 Create() 方法中

public ActionResult Create(int leaveType)
{
    var employee = DataAccess.GetEmployee(@User.Identity.Name);
    var rule = RuleAccess.GetEmployeeRules(employee).Where(x => x.ID == leaveType).FirstOrDefault();
    if (rule == null)
    {
        // Throw exception or redirect to an error page
    }
    var model = new LeaveApplicationViewModels();
    ....
    return View(model);
}

请注意,您的 LeaveApplicationViewModels 应包含其他属性,以便您可以避免所有这些 ViewBag 属性并生成强类型 View 。

关于javascript - 将选定的下拉菜单与条件进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37611977/

相关文章:

c# - 扩展用户管理器

c# - C++ CLI 句柄类型

asp.net - 无法使用 URL 显式从服务器查看 json 文件,其告诉文件未找到

javascript - PHP - 通知 : Undefined index: and not displaying data

javascript - 键入时检查输入(仅数字)

c# - 尝试访问回收站中的文件时出现 StyleCop 错误

asp.net - IP 而不是本地主机

asp.net - Team Build 2010 和 web.config 转换出现问题

javascript - Google Chrome : XMLHttpRequest. send() 在执行 POST 时不工作

javascript - ASP.NET MVC 验证 : result in a javascript property?