简体   繁体   中英

Post textarea using @Html.ActionLink - ASP.NET MVC 5

I know that this question was answered many times, but since I don't know much about javascript, and this is my first website, I followed the answer in this link. This is my code so far:

    <li>@Html.ActionLink("Save","SaveClass",new { path2=Model.path,code="xxx"},new { id="save"})</li>
@Html.TextAreaFor(m=>m.code, new { id = "code" })
<script>
       $("#save").click(function(evt) {
           var fakedUri = $("#save").attr("href");
           alert($('#code').val());
           var uri = $("#save").attr("href").replace("xxx", $("#code").val());
});
    </script>

And this is my controller:

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

The code always saves 'xxx' to the file, and throws:

The requested content appears to be script and will not be served by the static file handler.

How can I get it to work?

ActionLink helper generates a link and clicking on that will issue a GET request. Looks like you are trying to send the value of the text area through querystring to the next action method. But GET might not be the best solution to handle that. Querystring has a limit on how much data it can handle (varies for different browsers).

Ideally you should do a form submit, If you do not prefer a button, but want a link to initiate the form submit, that is possible with a little javascript.

@using(Html.BeginForm("SaveClass","YourControllerName"))
{
  @Html.TextAreaFor(m=>m.code)
  @Html.HiddenFor(s=>s.path)
  @Html.ActionLink("Save","SaveClass","YourControllerName",null,new { id="save"})

}

Now in your javascript, when click on the link, stop the default behavior (the default GET Action) and then submit the form where the clicked link is present. We can use the closest() method.

$(function(){

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

})

Make sure you use the correct parameter name (matching with the input name)

public ActionResult SaveClass(string path,string code)
{
   // to do  : return something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM