Analyzing a Specific DropDown Based on Condition

In my MVC project, I am working on a form that should be accessible based on certain conditions. The first view includes a dropdown list and a submit button. I want the value selected in the dropdown list to be passed and compared against a set condition. If the condition is not met, an alert should be shown instead of moving on to the form.

Below is the code snippet that I have implemented:

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);
}

I have utilized the ViewBag.comp1 and ViewBag.comp2 in my view for validation:

<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"
    }
) 

I have concerns about the URL manipulation where users can access the form directly by manually inputting the URL with a specific parameter value. Despite this, I still need the value of lv_type for my view. Any suggestions or guidance would be greatly appreciated.

Answer №1

It is crucial to perform validation on the server side, with client side validation seen as a helpful addition that can reduce the need for server calls. Providing options in a dropdown list to users and then restricting their selection can lead to a poor user experience. Instead, only present options that are relevant to the user.

Add a new method to your RuleAccess class, such as

GetEmployeeRules(Employee employee)
, which will return only the rules applicable to that employee.

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

Additionally, utilize a view model in the view

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

Then, in the ChooseType() method

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);
}

and in the view

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

Submit to a POST method which can easily return the view if invalid, or redirect to the Create method.

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

and in the Create() method

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)
    {
        // Handle exception or redirect to an error page
    }
    var model = new LeaveApplicationViewModels();
    ....
    return View(model);
}

Ensure that your LeaveApplicationViewModels includes additional properties to avoid using ViewBag properties and to create a strongly typed view.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve the complete user object in passport

Recently, I've been diving into utilizing Express authentication with Passport and React for the frontend. While working on this project, a question came up: How can I access the entire authenticated user object? This is what my database model looks l ...

A guide to showcasing JSON data on a webpage using JavaScript

I am currently working on a SOAP WSDL invocation application in MobileFirst. The response I receive from the SOAP WSDL is in JSON format and is stored in the result variable. When trying to access the length of the response using result.length, I encounter ...

Utilizing HighChart in ASP.NET MVC for Dynamic Data Visualization from a Database

I am completely new to ASP.NET MVC and I am trying to show data from a database in a Highchart using Visual Studio 2015. In my controller, I have the following code to retrieve data from the database: namespace HelloWorld.Controllers { public class Se ...

Retrieve the value of a JSON string

I'm having trouble accessing a json value in this example. No alert is being produced. Can you help me figure out what the problem is? This is the JSON data I am working with: { "response": [ { "id": "0", "elementName": "osname", "isEqual": t ...

Troubleshooting: Angular 2 View not reflecting changes after array push

I have encountered an issue with my two child components. They are both meant to share data from a json file that I load using the http.get/subscribe method. Oddly enough, when I try to push new data into the array, it doesn't seem to update in the vi ...

.NET Core BackgroundService with DI Scope set to null

My experience involves working with a .NET background service public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; private readonly ConvertService _convert; public Worker(ILogger<Worker&g ...

Implementing reCAPTCHA in Spring MVC with Ajax

I've been attempting to implement Google reCAPTCHA service with Spring MVC, but I keep encountering this error in the console: http://localhost:8080/spapp/ajaxtest.htm?name=frfr&surname=frfr&phone=edede…nGi3CCrD9GprYZDn8VHc-pN--SK-u_xoRKOrn ...

Utilize a single submit button to navigate through multiple pages dynamically using JavaScript

I would like to navigate to different rooms with just one button using JavaScript. For instance, there are three rooms: "Kitchen, Toilet, and Bedroom". How can I utilize JS to enter any of these rooms based on my selection? If I input "kitchen" in the text ...

The variable declared in the useState hook is not being properly updated within the callback function

const ModifiedTweet = ({ tweet, checkedList, setCheckedList }) => { const [isChecked, setChecked] = useState(false); useEffect(() => { if (checkedList.length === 0) { setChecked(false); } }, [checkedList, isChecked]); return ( ...

What is the best way to highlight matching words from a list in a Django form's textarea using JavaScript?

I am working with the following form: class TestForm(Form): testfield = CharField(widget=Textarea(attrs={'rows': 10, 'id': 'test'}), label='Input test text here') Displayed in my template along with this context ...

The div has extra white space at the bottom due to the Hide/Show content feature

Having trouble stretching a scrolling div to 100% of its parent container's height? The Hide/Show content feature is causing whitespace at the bottom of the div. Check out the jsfiddle here: http://jsfiddle.net/fkvftff2/1/ LATEST UPDATE: The issue a ...

How to Use AJAX, jQuery, and JSON to Send an Array to PHP

I'm attempting to send an associative array through AJAX $.post to a PHP script. Below is the code I am using: var request = { action: "add", requestor: req_id, ... } var reqDetails = $("#request_details").val(); ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

Guide to resetting all ReactiveVars to false in Meteor JS

I am currently working on a recipe template where I am using {{#each recipes}} to render the recipes. I have implemented ReactiveVar to toggle the edit form of each recipe from hide to show. Everything is functioning correctly, but I want to ensure that ...

Handling Camera Positioning and Direction in Three.js: Utilizing Orbit Controls and camera

Having trouble getting Orbit Controls to function correctly after setting the camera to : camera.up.set(0,0,1) This results in improper orbiting behavior, and there are some unresolved questions online addressing this issue: Three.js: way to change the u ...

Guide to automatically dismiss calendar popup after selecting a date

After selecting a date, how can I hide the calendar? I am currently utilizing Date-time-picker by DanyelYKPan. Is there a specific function that I should be using? Here is the code snippet: <div class="col-3"> <div class="form-group calenderF ...

Selenium C# is experiencing difficulties in running properly on localhost

I am attempting to scrape a website using Selenium and FireFox. While the Python code works fine, I encounter an issue in C# where I receive the error message: 'OpenQA.Selenium.WebDriverException: Cannot start the driver service on http://localhost:53 ...

Sending JavaScript functions to PHP files via Ajax

My Current Project: I am currently developing a script that provides users with choices and generates new options based on their selections. To achieve this, I have created two scripts - one for the HTML structure of my page and another for fetching serve ...

Adding a component to a slot in Vue.js 3

My Goal I aim to pass the Component into the designated slot. The Inquiry How can I effectively pass the Component into the slot for proper rendering? It works well with strings or plain HTML inputs. Additional Query If direct passing is not feasible, ...

Drawing a line beneath the mouse's center using JavaScript

Struggling with my JavaScript drawing tool, particularly the draw() function. The line is consistently off-center below the mouse cursor. How do I fix this issue? My aim is to have the line always follow the center of the mouse as it moves. Could someone c ...