0

ASP.NET, I have a controller with this GET method:

public ActionResult Index(String state, String searchNumber, String searchCustomer, int? page)
{
}

in the view I call it in this way:

$("#btnSearch").click(function (event) {
   var params = {
       state: '@ViewBag.State',
       searchNumber: $('input[name=searchNumber]').val(),
       searchCustomer: $('input[name=searchCustomer]').val()
   };

   var url = window.location.href + "/Index/?" + jQuery.param(params);
   window.location.href = url;
});

where the @ViewBag.State is a String received from the controller while the other fields are from texboxes.

Here a real example of the url value:

"http://localhost:49396/Orders/Index/?state=Opened&searchNumber=17&searchCustomer="

In the controller Index function the searchNumber variable is set to "17" but state to null.

Why the first one is not recognized?

5
  • Copying and pasting the given url in the browser leads to the correct behavior. Commented Mar 13, 2018 at 22:00
  • Add a console.log('@ViewBag.State') in your script and inspect the result. Is it what you expect? Commented Mar 13, 2018 at 22:04
  • Yes, it is correct. Commented Mar 13, 2018 at 22:09
  • 1
    Does not make sense (works fine for me) Commented Mar 13, 2018 at 22:13
  • Well, it is the actual code. I copied and pasted it from my solution. I try again. Thanks for the feedback. Commented Mar 13, 2018 at 22:14

1 Answer 1

1

@ViewBag.State is Razor syntax. Razor is working in your cshtml files, but javascript files are not parsed/processed.

One way to get the property anyway is to add an hidden field to your view with the value set to @ViewBag.State. Then read the value from the hidden field in javascript - just like you are already doing it for the other two properties.

Sign up to request clarification or add additional context in comments.

8 Comments

You're saying that the ViewBag value is "rendered" to the html when the page is served but after that javascript cannot access anymore to its value?
This is wrong (if it was an external js file, a value of "@ViewBag.State" would be sent, NOT null)
@StephenMuecke: That's true! I missed that.
Unfortunately even retrieving the field from an hidden input leads to the same behavior, There's something else wrong in my code.
@Mark: Razor is only processed in *.cshtml files. If you're javascript code is within your view file, it would be processed too, but if you wrote your js code in a separate file (I recommend that anyway) "@ViewBag.State" will not be processed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.