ASP.NET MVC 5- How can I post textarea value using @Html.ActionLink?

I have the following web page:
Code editor, and a list of Java files.And this is part of the partial view code :
<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>@Html.ActionLink("New", "NewClass", "Development", null, new { @class = "modal-link" })</li>
                                        <li>@Html.ActionLink("Save","SaveClass",new { path2=Model.path})</li>
                                        <li>@Html.ActionLink("Delete", "DeleteFile")</li>


                                    </ul>
                                </li>
                                <li>@Html.ActionLink("Compile", "Compile", "Development")</li>
                                <li>@Html.ActionLink("Run", "Run", "Development")</li>
                            </ul>

Open in new window

                    @Html.TextAreaFor(m=>m.code, new { id = "code" })

Open in new window


I want to pass the value of the textarea to the controller at the "Save" actionlink. I don't want to use buttons for design purposes. I also need to pass the path of the file to write the text to it (since path is always lost when navigating between controller and views). I googled for the problem but the solutions provided either didn't work or I didn't understand them. Is there an easy way to do that?


I tried this:
                                        <li>@Html.ActionLink("Save","SaveClass",new { path2=Model.path,code="xxx"},new { id="save"})</li>

 <script>
       $("#save").click(function(evt) {
           var fakedUri = $("#save").attr("href");
           alert($('#code').val());
    var uri = fakedUri.replace("xxx", $("#code").val());
});
    </script>

Open in new window


but it throws: The requested content appears to be script and will not be served by the static file handler.
leen emadComputer engineerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Prakash SamariyaIT ProfessionalCommented:
<li>@Html.ActionLink("Save","MySaveActionMethod","MyController",new { id="save"})</li>
Hope your action method has parameter in your controller (for e.g. below)
[HttpPost]
public  ActionResult  MySaveActionMethod(string codeValue){ 
...
}

Open in new window

Updated Script
<script>
       $("#save").click(function(evt) {
           var fakedUri = $("#save").attr("href");
           
           $.post( fakedUri , { codeValue: $("#code").val() } );
});
    </script>

Open in new window


but it throws: The requested content appears to be script and will not be served by the static file handler.
https://www.codeproject.com/Tips/882774/Fix-HTTP-Error-The-requested-content
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
leen emadComputer engineerAuthor Commented:
Thank you! It now saves the correct value, but I couldn't get rid of the error. I only get it when I redirect to "Index" ActionMethod, but if I access it directly it works.
0
Prakash SamariyaIT ProfessionalCommented:
but I couldn't get rid of the error. I only get it when I redirect to "Index" ActionMethod, but if I access it directly it works.
Have you tried resolution mentioned in link The requested content appears to be script...?

Could you show your code, which throws error (and also index method which is calling also) to check with?
0
Determine the Perfect Price for Your IT Services

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

leen emadComputer engineerAuthor Commented:
Yes, I did. still didn't work!

This is my controller
 StudentsCodes modelSC = new StudentsCodes();
        MicroG4 m4 = new MicroG4();

        public ActionResult Index()
        {
            modelSC.Student = (Student)CurrentUser;
            var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
            modelSC.Instructor =(Instructor) user;
            modelSC.path = "~/Content/" + CurrentUser.UserName + "/CompilerProject/src";
             return View(modelSC);
        }
 public PartialViewResult DevelopmentPartial(string path1)
        {
            modelSC.path = path1;
            modelSC.code = "";
            if (modelSC.path == null)
            {
                modelSC.code = "";
            }
            else
            {
                //var filename = Path.GetFileName("");
                try
                {
                   modelSC.code = System.IO.File.ReadAllText(Server.MapPath(modelSC.path));
                }
                catch (Exception e)
                {
                    modelSC.code = "";
                }
            }
            return PartialView(modelSC);

        }
 [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveClass(string path,string code)
        {
            modelSC.path = path;
            modelSC.code = code;
            System.IO.File.WriteAllText(Server.MapPath(modelSC.path), code);
            return RedirectToAction("Index");
        }

Open in new window

This is the index view:
@model application.Models.NewFolder1.StudentsCodes
@{
    ViewBag.Title = "Development";
    Layout = "~/Views/Shared/_Layout.cshtml";
  
}


<!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>
                @Model.Student.UserName
                <ul>
                    <li>
                        <span class="glyphicon glyphicon-folder-open"></span>
                        CompilerProject
                        <ul>
                            @{
                                var m = Directory.GetDirectories(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject"));
                                foreach (var subdir in m)
                                {
                                    var name = Path.GetFileName(subdir);
                                    <li>
                                        <span class="glyphicon glyphicon-folder-open"></span>
                                        @name
                                        <ul id="tree">
                                            @foreach (var file in Directory.GetFiles(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject/" + name)))
                                            {
                                                var filename = Path.GetFileName(file);

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

    
        <div id="partial">
        @{
            Html.RenderAction("DevelopmentPartial", new { path1 = Model.path});
        }
    </div>
   
    
    <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', { path1: filePath });
             });
         });
    </script>

    </body>




</html>

Open in new window

And this is the partial view:

@model application.Models.NewFolder1.StudentsCodes
<!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>
    <script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>


</head>
<body>
    
        @using (Html.BeginForm("SaveClass","Development"))
        {
            <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="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>@Html.ActionLink("New", "NewClass", "Development", null, new { @class = "modal-link" })</li>
                                        <li>@Html.ActionLink("Save","SaveClass","Development",null,new { id="save"})</li>
                                        <li>@Html.ActionLink("Delete", "DeleteFile")</li>


                                    </ul>
                                </li>
                                <li>@Html.ActionLink("Compile", "Compile", "Development")</li>
                                <li>@Html.ActionLink("Run", "Run", "Development")</li>
                            </ul>
                        </div>
                    </div>
                </div>
                    @Html.TextAreaFor(m=>m.code, new { id = "code" })
                @Html.HiddenFor(s => s.path)



            
            </div>

                    }
    

    <div id="modal-container" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-content"></div>
    </div>

    <style>
        .modal-content {
         width: 600px !important;
         margin: 30px auto !important;
     }
    </style>
    <script>
        $(function(){

            $("#save").click(function(e){
                e.preventDefault();
                $(this).closest("form").submit();
            });

        });

    </script>
    
   
    <script>

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

    <script type="text/javascript">
        $(function () {
            // Initialize numeric spinner input boxes
            //$(".numeric-spinner").spinedit();
            // Initialize modal dialog
            // attach modal-container bootstrap attributes to links with .modal-link class.
            // when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
            $('body').on('click', '.modal-link', function (e) {
                e.preventDefault();
                $(this).attr('data-target', '#modal-container');
                $(this).attr('data-toggle', 'modal');
            });
            // Attach listener to .modal-close-btn's so that when the button is pressed the modal dialog disappears
            $('body').on('click', '.modal-close-btn', function () {
                $('#modal-container').modal('hide');
            });
            //clear modal cache, so that new content can be loaded
            $('#modal-container').on('hidden.bs.modal', function () {
                $(this).removeData('bs.modal');
            });
            $('#CancelModal').on('click', function () {
                return false;
            });
        });
    </script>

    
</body>

</html>

Open in new window

0
leen emadComputer engineerAuthor Commented:
I didn't do anything, just restarted the laptop and the error is gone!! BUT, it's not showing the contents of the file onclick anymore! especially when redirecting to "index" from another webpage. But if I access it directly, it works.
0
Prakash SamariyaIT ProfessionalCommented:
It seems that StudentCodes and MicroG4 objects initialized only once!
Put  StudentCodes and MicroG4 objects initialization in Controller's constructor or in every action method!
Like below
public YOURCONTROLLER_CONSTRUCTOR()
{
            StudentsCodes modelSC = new StudentsCodes();
            MicroG4 m4 = new MicroG4();
}

        public ActionResult Index()
        {
           // IF you do have initialised in constructor, use below code
           // StudentsCodes modelSC = new StudentsCodes();
           // MicroG4 m4 = new MicroG4();

            modelSC.Student = (Student)CurrentUser;
            var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
            modelSC.Instructor =(Instructor) user;
            modelSC.path = "~/Content/" + CurrentUser.UserName + "/CompilerProject/src";
             return View(modelSC);
        }

Open in new window

1
leen emadComputer engineerAuthor Commented:
I tried but it still doesn't work! Now when I click on a file, it passes the correct path to the script, but it doesn't even call the action method.
But it only works if I access the "Development Index" directly. Why would the same code execute correctly if the "Index" is accessed directly, but wouldn't if I redirect to it or access it from another webpage?

I'm not sure if this is related, but the dropdown "file" menu in the image above doesn't always work. I mean, at the beginning it works, then if I click on a file and the partial view reloads, it doesn't (it doesn't show the list <New, Save, Delete>). But if I click on a file again it works, and so on...
0
leen emadComputer engineerAuthor Commented:
I sloved it by updating  the script that loads the partial view:
  <script type="text/javascript">
         $(document).ready(function () {
             $('.filelist').on('click', function (e) {
                 e.preventDefault();
                 alert('Im clicked on filePath = ' + $(this).attr('value'));
                 var filePath = $(this).attr('value');    //value is attribute set in Html
                 $('#partial').load('@Url.Action("DevelopmentPartial", "Development")', { path1: filePath });
             });
         });
    </script>

Open in new window

The partial view reloads correctly again, but I couldn't solve the problem with the "File" dropdown menu.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET MVC

From novice to tech pro — start learning today.