The view page encounters an issue when attempting to load a null element

I am currently working with a JavaScript function that generates links on my webpage based on the user's selection from a DropDown menu. I have implemented checks for this JavaScript function in two scenarios: when the user selects an option from the DropDown (using the "onchange" attribute) and when the page is initially loaded. The problem arises when the page is loaded without any element in the viewbag, causing my JavaScript to fail in generating links in the absence of necessary information from the viewbag.

<p>Search by: @Html.DropDownList("tipoPesquisa", ViewBag.DropDownPesquisa as SelectList, new { onchange = "alteraFiltro()" }) 

<div id="dadosFornecedor">
    @if (ViewBag.CurrentFornecedor != null)
    {
        <fieldset>
            <legend>@ViewBag.CurrentFornecedor.RazaoSocial</legend>
            <b>Razão Social:</b> @ViewBag.CurrentFornecedor.RazaoSocial <b>Endereço:</b> @ViewBag.CurrentFornecedor.Endereco
            @Html.Hidden("idFornecedor", new { IdFornecedor = ViewBag.CurrentFornecedor.IdFornecedor })
            <input type="button" class="btn" onclick="removerFornecedor();" value="Remove Supplier" />
            <br />
            <br />
        </fieldset>
        <br />

    }
</div>

<script type="text/javascript">
    $(function () {

       alteraFiltro();
    });

    function removerFornecedor() {
        var div = $("#dadosFornecedor");
        var hidden = $("#idFornecedor");
        div.empty();
    
        div.append("<input type='hidden' name='deletarFornecedor' value='true' />")
    }

    function alteraFiltro() {
        var urlCodigo = $("#linkCodigo");
        var urlLancamento = $("#linkLancamento");
        var urlPagamento = $("#linkPagamento");
        var urlFornecedor = $("#linkFornecedor")
        var dropValue = $("#tipoPesquisa").val();
        var hidden = $("#idFornecedor");

        if (hidden.val() == "" || hidden.val() == null || hidden == null) {
            // Update the links accordingly
        } else {
            // Update the links accordingly
        }
    }
</script>

Answer №1

If you are experiencing an issue with ViewBag.CurrentFornecedor not having a value upon initial view loading, consider adjusting your javascript in the following manner:

 var hidden = $("#idFornecedor");

 if (hidden.val() == "" || hidden.val() == null || hidden == null) {

 // ...

 }
 else {

    urlCodigo.attr("href", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c0f1d15181d0f38150a190e0f1d0f0f130e08330e18190e413c2a15190b3e1d1b523f1318151b132f130e082c1d0e11">[email protected]</a>&idFornecedor=" 
         + @{ViewBag.CurrentFornecedor != null ? ViewBag.CurrentFornecedor.IdFornecedor : -1} 
        + "&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abc8ded9d9cec5dfedc2c7dfced996ebfdc2cedce9cacc85e8ded9d9cec5dfedc2c7dfced9">[email protected]</a>&currentDrop=" + dropValue + "");

    // ...

}

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

What is the purpose of <Component render={({ state }) => {} /> in React?

Currently delving into the world of ReactJS, I decided to implement fullPageJS. It seems to be functioning properly, although there are certain syntax elements that remain a mystery to me. Take a look at the component below: function home() { return ( ...

Having issues with ASP.NET MVC AJAX PartialView not loading Telerik UI components

I am facing an issue with a PartialView that I update using AJAX. The HTML elements load correctly when updating the Div with AJAX, but the Telerik chart is not loading. The datasource in the chart does not call the Action method: .DataSource(ds => ds. ...

Fluctuating Values in Array Distribution

I have a set of users and products that I need to distribute, for example: The number of values in the array can vary each time - it could be one value one time and three values another time. It is important that each user receives a unique product with ...

Fetching from the same origin results in a null comparison issue due to HTTP CORS restrictions

Encountering an issue where a simple same-origin fetch("fetch.xml") call fails, resulting in a console error message Access to fetch at 'http://127.0.0.1:8000/fetch.xml' from origin 'null' has been blocked by CORS policy: Th ...

What is the process for adding elements to an object in Angular JS?

My goal is to send data to an ng-object after filling out and submitting an HTML form with user-defined values. However, after pressing submit, the values are being duplicated. I have attempted to clear the data by using $scope.user > $scope.user=&apos ...

The search feature in AngularJS with filter appears to be malfunctioning

I've been attempting to use the angularjs filter method for searching, but it doesn't seem to be working correctly. Despite not seeing any errors in the console, the search results aren't showing up. Can someone lend a hand with this? Below ...

What are the steps to rename a file in Parcel without using automated tools?

Whenever I attempt to execute npm start or npm build, an error occurs stating that unknown: Entry /mnt/c/Users/kabre/Desktop/18-forkify/index.html does not exist. I was informed that Parcel could be renaming my index.html automatically. It's a bit con ...

The type unknown[] cannot be assigned to type React.ReactNode

import * as React from 'react'; import { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material'; import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined'; import NotificationsNoneOutl ...

What benefits come from employing jQuery for data storage techniques?

After learning more about jQuery data storage, I have a question. Is there any advantage to using either of these methods: $('#editCity').data('href', "xx"); var a = $('#editCity').data('href'); or $('#edit ...

Attempting to compare the HTML datetime with the current time in order to implement conditional formatting

I am working with a SharePoint discussion list that includes a field named "Last Updated." My goal is to identify and highlight rows where the last update was more than 1 hour ago. Here is my current approach: <html> <head> <sc ...

Guide to connecting two separate components from distinct pages in React/MUI

My setup involves two pages: Appbar.js, where I have a top appbar and a Navigation Menu Icon Button that triggers the display of my Drawer (Material UI) in TempDrawer.js. Initially, everything worked fine when all the code was placed in the Appbar.js file ...

Unable to include the variable "$localStorage"

While working on my method in app.js, I encountered the following error: Uncaught Error: [$injector:strictdi] function($rootScope, $q, $localStorage, $location) is not using explicit annotation and cannot be invoked in strict mode http://errors.angula ...

Using Javascript and jQuery to create an infinite animated background change with fade effect

I am struggling to figure out how to automatically change the background of a div every 3 seconds, looping through a series of images. I posted about this issue before but didn't receive much help. function animate() { change1(); change2() ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

Display a JSX component based on a specific condition

As a newcomer to React, I am currently working on the navigation portion of my Navbar.js using the react-router-dom useLocation hook. I have successfully obtained the active path that leads to views and now I want to display custom text when a user reaches ...

Tips for automatically updating the time in a React application while utilizing the 'date-fns' library

I've been working on my personal Portfolio using React and I'm looking to add a feature on the landing page that showcases my local time and timezone to potential recruiters. However, there's a small hiccup in my implementation. The displaye ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

Utilize new metadata options to incorporate an external style and script file

I'm looking to incorporate external CSS and scripts into my NextJS app (NextJS version 13.4.13). Here's what I need: Style https://company.com/statics/1/package/dist/1/styles/dls.min.css Script https://company.com/statics/1/package/dist/1/ ...

Encountering a "Connection Refused" error when attempting to test a React and Express application

Currently, I am developing an order system using React for the frontend (port 3000) and Express for the backend (port 3001). Everything functions perfectly when tested on the same MacBook that hosts the node project. However, when testing it on a differen ...