10

I have to write C# code for showing and hiding div in MVC3 for various controls based on switch case in C# .How can it be done without using JQuery Show or hide.. but in fully server side..?

3 Answers 3

11

Add your switch statement directly into your .cshtml file. It will all be server-side at that point.

Controller:

public ActionResult Page()
{
    string data = "value1";
    return View(data);
}

CSHTML:

@model string; // this should be the Type your controller passes

<div>some html content</div>
@switch(Model) // Model is how you access your passed data
{
    case "value1":
        <div>...</div>
    break;
    case "value2":
        <div>...</div>
    break;
}
<div>more html content</div>
Sign up to request clarification or add additional context in comments.

3 Comments

@vignesh, You can also use ViewBag or ViewData to pass values from controller to view.
Yes, anything is possible. Your object that you're sending to your View can be anything, including a string of HTML.
Clearly this works. My question is whether the logic that determines whether a div will be shown in HTML or not belongs in the view document. Is this something that can or should be moved to some other document? I've heard that the controller shouldn't contain this logic either, so is there a more fitting place?
0

W3c has a Article about Logic Conditions

Use this sample

@switch(value)
{
    case "YourFistCase":
        <div>Login</div>;
    break;
    case "YourSecondeCase":
        <div>Logout</div>;
    break;
}

or see sample

// Use the @{ } block and put all of your code in it
@{
    switch(id)
    {
        case "test":
            // Use the text block below to separate html elements from code
            <text>
                <h1>Test Site</h1>
            </text>
            break;  // Always break each case
        case "prod":
            <text>
                <h1>Prod Site</h1>
            </text>
            break;
        default:
            <text>
                <h1>WTF Site</h1>
            </text>
            break;                   
    }
}

1 Comment

Is it possible to move all this code to controller...than in cshtml inline
-2

Why you use switch statement??

Do you like if condition???

for

<% if(CheckYourCondition){ %>

   <div class="TestClass">
   Test
   </div>

<% } %>

Comments

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.