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

leen emad
leen emad used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
IT Professional
Top Expert 2015
Commented:
<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
leen emadComputer engineer

Author

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.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
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?
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:
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

leen emadComputer engineer

Author

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.
Prakash SamariyaIT Professional
Top Expert 2015

Commented:
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

leen emadComputer engineer

Author

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...
leen emadComputer engineer
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.

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