Avatar of leen emad
leen emad
Flag for Jordan asked on

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

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?
JavaScriptjQuery.NET MVC.NET ProgrammingC#

Avatar of undefined
Last Comment
Prakash Samariya

8/22/2022 - Mon
Prakash Samariya

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 emad

ASKER
If I pass another argument in
.load 

Open in new window

it always becomes non-clickable.
Prakash Samariya

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
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
leen emad

ASKER
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 Samariya

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 emad

ASKER
I'm trying to debug it , I'll let you now asap.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
leen emad

ASKER
After debugging , when I click on a filename , it redirects to the Partial view controller but passes null.
Prakash Samariya

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 emad

ASKER
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?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
leen emad

ASKER
Actually , no it doesn't get the path value.
Prakash Samariya

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 emad

ASKER
The value is '0'
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Prakash Samariya

Can you send the generated html code for li tag?
<li class="filelist" value=".....
leen emad

ASKER
Do I have to use the debugger mode to get it?
leen emad

ASKER
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

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Prakash Samariya

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 emad

ASKER
When I pass something like "1" in the value, or @("string"), it works. but it looks like it doesn't pass  variables.
Prakash Samariya

Can you provide complete HTML generated code to check?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
leen emad

ASKER
From the browser?
Prakash Samariya

Yes
leen emad

ASKER
<!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

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
leen emad

ASKER
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 emad

ASKER
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 Samariya

Can you please check whether your controller action method gets the value? (put debug point in action method and check)
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER CERTIFIED SOLUTION
Prakash Samariya

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
leen emad

ASKER
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 Samariya

I guess, now you should get the filepath in your partial view to load content in editor!
leen emad

ASKER
In the debugger mode, it finally worked !!!
sorry for the trouble and thank you for following up with my problem.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Prakash Samariya

You are welcome :)