i’m new in mvc and i want to show/hide a html control after a jquery ajax call.
In ASP.NET is simple like set Label.Visible = false.
i have a razor view with something like this:
@if (ViewBag.Show)
{
Html.Label("Test");
}
<input id="idClick" type="button" value="Click"/>
and a script with jquery to call an action
$("#idClick").click(function() {
$.ajax({
url: '/Test/ShowLabel',
type: 'GET',
dataType: 'json'
}
});
In my index view i set:
ViewBag.Show = false;
in the action:
public void ShowLabel()
{
ViewBag.Show = true;
}
but i can’t get the label showed
i want to avoid render the control and then apply a style to hide it
How can i do this?
I assume the following code is also on said “index view”:
If that is the case, you are overwriting
ViewBag.Showin the index view when you useViewBag.Show = false;. Remove that line and it will show your textbox.Edit
I just noticed your “action” is returning void–meaning no view will get rendered if this action method gets called. It seems you need to read up more on how ASP.NET MVC works, or rephrase your question.
If you do not set
ViewBag.Show = true;in the index action method (or whichever one is being used to create your view) then ViewBag.Show will default to false. Ensure you are setting the variable where it is actually being called and don’t overwrite it in your view.Edit 2
In response to your edit, do not use the
ViewBagat all to hide your controls. Instead, just pass in an anonymous type to the HTML helper:or use a CSS class instead:
Edit 3
Your question is really hard to follow and I see that you were trying to use Ajax to send back the
ViewBagto the page. You can’t do this. TheViewBagis a server-side only “bag” that is only used to initially render the page. You can either return Json/Xml from your action method to indicate if the label should be hidden or visible, or use a partial page update.I think based on the amount of scattered information you have, it might be wise to start with synchronous pages first, and get a feel for how ASP.NET MVC works before tossing in Ajax calls.
Edit 4
It seems that you want to be able to change the visibility of your label based on the results of an Ajax call. Since
ViewBagis not going to change a thing when your user already has the page rendered, you need to return the result back to your page via JSON, XML, or a partial page refresh. The simplest would be to return some JSON:Then add an ID to your label:
And then make your Ajax call:
Final Edit
Since I see you want this for validation, you can save yourself a lot of headache and use the built-in mechanisms with Remote Validation.