If either in the view or controller

Cannot create the (if) and (else) operator in (View). The purpose of the instruction 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 to hide code, or is it better to match the task controller.

The code should be displayed only if the search query is not zero. The code below is a search form.

 @using (Html.BeginForm()) { <div id="borderSearch"> @Html.TextBox("searchString", "") </div> <input type="submit" value="Search News Archives" /> } 

Some controller codes:

  if (Request.HttpMethod == "GET") { searchString = search; } else if (searchString == "") { return RedirectToAction("ErrorSearch"); } else { page = 1; } ViewBag.search = searchString; 

Any advice on how to do this would be welcome.

+4
source share
2 answers

Well, I'm not 100% sure if I fully understand your question, but if I hear you correctly, you don’t know how to put an if statement around the first block of code and / or you have to do it.

Firstly, here's the β€œhow” - you just use @if (sorry if this seems obvious - I'm not trying to offend 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 is whether to show the expression β€œif” in the view to show or hide the HTML? Oh sure. This is what the point of view in MVC is for. The controller is designed to perform queries and calculate the number of results and manipulate data, but this view should accept the results and actually output them in HTML. Therefore, in this case, we rely on the controller to set the ViewBag.search value, and then, based on this view, can display or hide a specific HTML block. The controller does not and should not know about HTML.

Does this answer your question?

PS- Here's a quick quick reference to Razor syntax if you're interested:
http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

+5
source
 @if(!string.IsNullOrEmpty(ViewBag.Search)) { <div id="clearbuton"> <p>@Html.ActionLink("Clear", "")</p> <p> @String.Format("Total of {0} results", ViewBag.CountRecords)</p> </div> } 

See this blog post by ScottGu

+3
source

Source: https://habr.com/ru/post/1390760/


All Articles