ASP.NET MVC -Update model when click on <li> element

leen emad
leen emad used Ask the Experts™
on
The webpage contains a text editor , and a side bar contains a list of files. I want that when the user clicks on a file, its contents'll be displayed in the text editor.
I used a partial view for the text editor, and the main view for the sidebar.

This is my controller:
 public ActionResult Index()
        {
            StudentsCodes model = new StudentsCodes();
            model.Student = (Student)CurrentUser;
            var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
            model.Instructor =(Instructor) user;
            model.path = "~/Content/" + CurrentUser.UserName + "/CompilerProject/src";
             return View(model);
        }
 public PartialViewResult DevelopmentPartial(StudentsCodes path)
        {
            var x = path.path;
            return PartialView(path);

        }

Open in new window


part of Index view:
 @foreach (var file in Directory.GetFiles(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject/" + name)))
                                            {
                                                var filename = Path.GetFileName(file);

                                                <li class="filelist" onclick="@(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + @filename)">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    @filename
                                                </li>
                                            }

Open in new window

 <div id="partial">
        @{
            Html.RenderPartial("DevelopmentPartial", new application.Models.NewFolder1.StudentsCodes
            {
                Student = Model.Student,
                Instructor=Model.Instructor,
                code=Model.code,
                path=Model.path
            });
        }
    </div>
    <!--

    -->

    <script>
        $(document).ready(function () {
            $(".filelist").on("click",function (e) {
                $("#partial").load('DevelopmentPartial');

            });
        });
    </script>

Open in new window


partial view:
 </div>
        @using (Html.BeginForm())
        {
            var fileContents = "";
            if (Model == null || Model.path==null)
            {
                fileContents = "";
            }
            else
            {
                //var filename = Path.GetFileName("");
                try
                {
                    fileContents = System.IO.File.ReadAllText(Server.MapPath(Model.path));
                }
                catch(Exception e)
                {
                    fileContents = "";
                }
            }
                @Html.TextArea("code", fileContents, new { id = "code" })
        }

</div>

Open in new window


In my code, the editor refreshes but it's empty. The model passed is always null.  And even though list elements are clickable, they look like a normal text.
What am I doing wrong? Am I updating the "Model.path" wrongly?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
Because, you just calling Partial View in jQuery load method!
<script>
        $(document).ready(function () {
            $(".filelist").on("click",function (e) {
                $("#partial").load('DevelopmentPartial');

            });
        });
    </script>

Open in new window

Change in HTML!
 <li class="filelist" value="@(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + @filename)">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    @filename
                                                </li>

Open in new window

You have to pass selected file path to it to work it out!
<script>
        $(document).ready(function () {
            $(".filelist").on("click",function (e) {
               var filePath = (this).value;    //value is attribute set in Html
                $("#partial").load('DevelopmentPartial',{path: filePath});

            });
        });
    </script>

Open in new window

Hope this will work!
leen emadComputer engineer

Author

Commented:
If I pass another argument in
.load 

Open in new window

it always becomes non-clickable.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
it always becomes non-clickable.
It is not true! You are just loading another page's content to particular DIV, so if event is written for separate element, then it will always works!
Hope it clears now!

And your event is occured on "$(".filelist").on("click",function (e) {" which is different
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

leen emadComputer engineer

Author

Commented:
I tried your solution and it looks reasonable , but still having the same problem.
 This is my first website and I don't know much about JavaScript.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
Did you get the file path on clicked on list in below code?
var filePath = (this).value;
Did your controller gets the path in back-end using?
$("#partial").load('DevelopmentPartial',{path: filePath});
leen emadComputer engineer

Author

Commented:
I'm trying to debug it , I'll let you now asap.
leen emadComputer engineer

Author

Commented:
After debugging , when I click on a filename , it redirects to the Partial view controller but passes null.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
Did you get the file path on clicked on list in below code?
var filePath = (this).value;

It should get file path of clicked Li tag
leen emadComputer engineer

Author

Commented:
The debugger skips any code that is not C# , so I'm not sure.
Just for me to understand , in :
{path: filePath}

Open in new window

path is Model.path? or the value to be passed to the controller?
leen emadComputer engineer

Author

Commented:
Actually , no it doesn't get the path value.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
path is Model.path?
No, it a variable used in controller method

In jQuery, put alert in
var filePath = (this).value;
alert(filePath);

Make sure it is getting value
leen emadComputer engineer

Author

Commented:
The value is '0'
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
Can you send the generated html code for li tag?
<li class="filelist" value=".....
leen emadComputer engineer

Author

Commented:
Do I have to use the debugger mode to get it?
leen emadComputer engineer

Author

Commented:
Using HTML encode:                                              
  &lt;li class=&quot;filelist&quot; value=&quot;@(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + filename)")&quot; &gt;

Open in new window

And this is how it looks in the browser:
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\alaa.java" >

Open in new window

Prakash SamariyaIT Professional
Top Expert 2015

Commented:
Your HTML generation for LI is okay!
In my example it is getting value of <LI> tag
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<meta http-equiv="Access-Control-Allow-Origin" content="*"/>
</head><body>
<h1>Test class value</h1>
<ul>
<li class='filelist' value="1">1 item</li>
<li class='filelist' value="2">2 item</li>
<li class='filelist' value="3">3 item</li>
</ul>
<div id="checkValue">Your clicked Item will display here!</div>
<div id="partial"></div>
<script>
        $(document).ready(function () {
            $(".filelist").on("click",function (e) { 
				alert('Im clicked on filePath = '+(this).value);
				var filePath = (this).value;    //value is attribute set in Html
                                $("#partial").text('You Clicked on '+filePath+' item!\tIt will load in a moment!');
				$("#partial").load('DevelopmentPartial',{path: filePath});
            });
        });
    </script>
</body>
</html>

Open in new window

In above code I used alert() to be display when any LI tag is clicked. This alert will show the selected LI tag's value.
If it is showing selected LI tag's value, then jQuery part is okay!

Please just confirm that you are getting alert with proper filepath
leen emadComputer engineer

Author

Commented:
When I pass something like "1" in the value, or @("string"), it works. but it looks like it doesn't pass  variables.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
Can you provide complete HTML generated code to check?
leen emadComputer engineer

Author

Commented:
From the browser?
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
Yes
leen emadComputer engineer

Author

Commented:
<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <t
       itle>Development</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.8.3.js"></script>


</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/">CPE543 project</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="/">Home</a></li>
                    <li><a href="/Development">Development</a></li>
                    <li><a href="/Development/Micro">Micro.g4</a></li>
                    <li><a href="/Home/Test">Test</a></li>
                    <li><a href="/Home/Submit">Submit</a></li>
                    <li><a href="/Account/Logout">Logout</a></li>
                </ul>
                </div>
            </div>
    </div>
    <div class="container body-content">
        <br/>
        <br/>
        


<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="∼/Content/bootstrap.css" rel="stylesheet" />
    <link href="∼/Content/bootstrap-theme.css" rel="stylesheet" />

        <script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script type="text/javascript" src="/Scripts/jquery-3.1.1.js"></script>

        <script src="/Scripts/bootstrap.min.js"></script>

    

</head>
<body>
    <div class="navbar navbar-inverse " style="left:0; width:300px;bottom:3px; position:fixed; top:50px; color:#4e4a4a; font:bold;">
        <ul class="nav nav-pills nav-stacked">
            <li>
                <span class="glyphicon glyphicon-folder-open"></span>
                Auy00114
                <ul>
                    <li>
                        <span class="glyphicon glyphicon-folder-open"></span>
                        CompilerProject
                        <ul>
                                    <li>
                                        <span class="glyphicon glyphicon-folder-open"></span>
                                        external libraries
                                        <ul id="tree">
                                        </ul>
                                    </li>
                                    <li>
                                        <span class="glyphicon glyphicon-folder-open"></span>
                                        src
                                        <ul id="tree">
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\alaa.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    alaa.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\Driver.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    Driver.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\Instruction.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    Instruction.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\Label.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    Label.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\Micro.tokens">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    Micro.tokens
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\MicroBaseVisitor.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    MicroBaseVisitor.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\MicroLexer.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    MicroLexer.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\MicroLexer.tokens">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    MicroLexer.tokens
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\MicroParser.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    MicroParser.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\MicroVisitor.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    MicroVisitor.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\MyVisit.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    MyVisit.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\new.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    new.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\Scope.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    Scope.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\SubScope.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    SubScope.java
                                                </li>
                                                <li class="filelist" value="D:\cloud\asp\application\application\Content\Auy00114\CompilerProject\src\Variables.java">
                                                    <span class="glyphicon glyphicon-file"></span>
                                                    Variables.java
                                                </li>
                                        </ul>
                                    </li>

                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </div>

    
        <div id="partial">
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />

    <script src="/Scripts/codeMirror-2.37/lib/codemirror.js"></script>
    <script src="/Scripts/codeMirror-2.37/mode/clike/clike.js" type="text/javascript"></script>
    <link href="/Scripts/codeMirror-2.37/lib/codemirror.css" rel="stylesheet" type="text/css" />
    <link href="/Scripts/codeMirror-2.37/theme/lesser-dark.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-3.1.1.min.js"></script>
    <link href="∼/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="/Scripts/bootstrap.min.js"></script>



</head>
<body>
    <div class="CodeMirror cm-s-lesser-dark cm-error cm-bracket" style="position:absolute;border:solid;top:150px;left:450px;width:700px">
        <div class="navbar navbar-inverse" style="border:none">
            <div class="container-fluid">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                </div>
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav">
                        <li role="presentation" class="dropdown">
                            <a class="dropdown-toggle" data-toggle="dropdown">
                                File <span class="caret"></span>
                            </a>
                            <ul class="dropdown-menu">
                                    <li><a href="/Development/CreateNewFile">New</a></li>
                                    <li><a href="/Development/UpdateFile">Save</a></li>
                                    <li><a href="/Development/DeleteFile?VirtualPath=~%2FContent%2FAuy00114%2FCompilerProject%2Fsrc">Delete</a></li>


                            </ul>
                        </li>
                        <li><a href="/Development/Compile">Compile</a></li>
                        <li><a href="/Development/Run">Run</a></li>
                    </ul>
                </div>
            </div>
        </div>
<form action="/Development/Index" method="post"><textarea cols="20" id="code" name="code" rows="2">
</textarea></form>
</div>




    <script>

        var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/x-java",
            theme: "cm-s-lesser-dark"
        });
    </script>
    

<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
    {"appName":"Chrome","requestId":"475cf23b349f4d82928f04112d33521f"}
</script>
<script type="text/javascript" src="http://localhost:50070/efbd8f69ba88447fb1b0d01443973ec1/browserLink" async="async"></script>
<!-- End Browser Link -->

</body>

</html>



    </div>
    
    
     <script>
         $(document).ready(function () {
             $(".filelist").on("click", function (e) {
                 alert('Im clicked on filePath = ' + (this).value);
                 var filePath = (this).value;    //value is attribute set in Html
                 $("#partial").load('DevelopmentPartial', { path: filePath });
             });
         });
    </script>
</body>





</html>

       <!--<hr />--> 
       
    </div>
            <script src="/Scripts/jquery-3.1.1.js"></script>

            <script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>

            
</body>
</html>

Open in new window

leen emadComputer engineer

Author

Commented:
I updated the script as the following:
 
<script>
        $(".filelist").click(function() {

            var filepath = $(".filelist").attr("value");
            alert(filepath);
            $("#partial").load("DevelopmentPartial", { path: filepath });
            }); 
    </script>

Open in new window

Now it passes the path to the script, but not to the controller .

Edit:
It actually passes the value of the first path, regardless of the item clicked.
leen emadComputer engineer

Author

Commented:
Now , finally this code passes the correct path to the script, but also it doesn't display the contents of the file.

<script>
         $(document).ready(function () {
             $('.filelist').on('click', function (e) {
                 alert('Im clicked on filePath = ' + $(this).attr('value'));
                 var filePath = $(this).attr('value');    //value is attribute set in Html
                 $('#partial').load('DevelopmentPartial', { path: filePath });
             });
         });
    </script>

Open in new window

Prakash SamariyaIT Professional
Top Expert 2015

Commented:
Can you please check whether your controller action method gets the value? (put debug point in action method and check)
IT Professional
Top Expert 2015
Commented:
public PartialViewResult DevelopmentPartial(StudentsCodes path)

Open in new window

It won't work as your code accepts complete model, and you are passing only filepath!

so change DevelopmentPartial controller method as below to make it workable
public PartialViewResult DevelopmentPartial(String path)
        {
            return PartialView(path);
        }

Open in new window

leen emadComputer engineer

Author

Commented:
Yes , you're right. I changed it now but still doesn't work :/
I'll try debugging it again and see if it'll work now.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
I guess, now you should get the filepath in your partial view to load content in editor!
leen emadComputer engineer

Author

Commented:
In the debugger mode, it finally worked !!!
sorry for the trouble and thank you for following up with my problem.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
You are welcome :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial