Trouble creating an (if) and (else) statement in a (View). The purpose of the statement is to hide the following code:
<div id="clearbuton"><p>@Html.ActionLink("Clear", "")</p>
<p> @String.Format("Total of {0} results", ViewBag.CountRecords)
</div>
Is the view the best place for hiding the code or would a controller be better suited to the task.
The code is only to be displayed if a search query is not null. The code below is the search form.
@using (Html.BeginForm())
{ <div id="borderSearch">
@Html.TextBox("searchString", "")
</div>
<input type="submit" value="Search News Archives" />
}
Some code from the controller:
if (Request.HttpMethod == "GET")
{
searchString = search;
}
else if (searchString == "")
{
return RedirectToAction("ErrorSearch");
}
else
{
page = 1;
}
ViewBag.search = searchString;
Any advice on how to accomplish this would be welcome.
OK, I'm not 100% sure if I understand your question completely, but if I'm hearing you correctly, you're not sure how to put an if statement around the first block of code and/or whether you should do so.
First, here's the "how"-- you just use @if
(forgive me if this seems obvious-- I'm not trying to insult your intelligence):
@if (!string.IsNullOrEmpty(ViewBag.search))
{
<div id="clearbuton"><p>@Html.ActionLink("Clear", "")</p>
<p> @String.Format("Total of {0} results", ViewBag.CountRecords)</p>
</div>
}
Now the reasoning-- should you put an "if" statement in the view to show or hide HTML? Yes, absolutely. That is what the view is designed for in MVC. The controller is for doing the queries and calculating counts of results and manipulating data, but it is the view that needs to take the results and actually render them to HTML. So in this case we rely on the controller to set the value of ViewBag.search
then based on that, the view can show or hide a specific block of HTML. The controller doesn't (and shouldn't) know about the HTML.
Does that answer your question?
P.S.- Here is a handy quick reference on Razor syntax if you are interested:
http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With