Unable to read value from document

Viewed 191

I'm a novice in MVC, Below is my code I am unable to read the value of an ID and use that in an decision statement, I am getting "The name "Text" does not exist in current context", I need to work on the if statement based on the value I get from my document.getElementById

    @{

        var grid = new WebGrid(Model.Abc, canPage: true, canSort: true, rowsPerPage: 50);
    }


    @{
        var gridColumnsNew = new List<WebGridColumn>();
        gridColumnsNew.Add(grid.Column("Details", header: "Id"));
       
        <text>
            var obj = document.getElementById("NextAction").value;
        </text>

        if (@text.obj == "Start")
        {
            gridColumnsNew.Add(grid.Column("Temp"));

        }
        
}
4 Answers

Try using

document.getElementsByName("NextAction").value;

I have seen in my case that Blazor changes Id to name. Note: I am using DevexpressBlazor

Did you checked if you are able to see on the html generated that ID?

If yes, Did you have any JS error before?

Looks like the ID not was generated or the place where you are run the getElementById don't have visibility to your specific code.

You are mixing razor syntax and javascript. The line var obj = document.getElementById("NextAction").value; is javascript and should go inside <script> tag. You can't call javascript functions from razor code.

Solution:

Assuming you have a controller named GridController.cs and a view named Grid.cshtml. Inside your controller add a new HttpPost action:

[HttpPost] 
public IActionResult NextAction(string nextAction)
{
    ViewData["NextAction"] = nextAction;
    return View("Grid");
}

Inside the view add a form that posts the nextAction value to the controller:

<form asp-action="NextAction" asp-controller="Grid">
    <input type="hidden" value="Start" name="nextAction" />
    <button type="submit">Start</button>
</form>

The controller added the NextAction value in the ViewData dictionary so now the view can access it:

@{
    var gridColumnsNew = new List<WebGridColumn>();
    gridColumnsNew.Add(grid.Column("Details", header: "Id"));
   
    if (ViewData["NextAction"] == "Start")
    {
        gridColumnsNew.Add(grid.Column("Temp"));
    }
}

You are getting that error because you are using @text.obj. In Razor, once you attached @ before any identifier, it considers it a C# or VB variable.

Since we don't have your entire page, you may need to clarify where the source of the NextAction. It will be helpful. See a sample of something similar.

  @if(item.Ward == "start")
     {
          gridColumnsNew.Add(grid.Column("Temp"));
     }

The item is from the model I am iterating to form the grid.

Related