简体   繁体   English

使用@ Html.ActionLink发布textarea-ASP.NET MVC 5

[英]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. 我知道这个问题已经被回答了很多次,但是由于我对javascript的了解不多,而且这是我的第一个网站,因此我遵循了链接中的答案。 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: 该代码始终将“ xxx”保存到文件中,并抛出:

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. ActionLink帮助程序将生成一个链接,然后单击该链接将发出GET请求。 Looks like you are trying to send the value of the text area through querystring to the next action method. 似乎您正在尝试通过querystring将文本区域的值发送到下一个action方法。 But GET might not be the best solution to handle that. 但是GET可能不是解决此问题的最佳解决方案。 Querystring has a limit on how much data it can handle (varies for different browsers). Querystring对其可以处理的数据量有限制(不同的浏览器会有所不同)。

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. 理想情况下,您应该进行表单提交,如果您不喜欢按钮,但是想要一个链接来启动表单提交,则可以使用一些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. 现在,在您的JavaScript中,单击链接时,停止默认行为(默认的GET Action),然后提交存在单击链接的表单。 We can use the closest() method. 我们可以使用closest()方法。

$(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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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