简体   繁体   English

将值从javascript传递到mvc控制器

[英]Passing value from javascript to mvc controller

I am using tinyMCE (a rich text editor in js). 我正在使用tinyMCE(js中的富文本编辑器)。 Currently, I have a function as such: 目前,我有这样的功能:

   function GetEditorValue() {
        var val = tinyMCE.get('valueTextArea').getContent()

    }

which returns the text that was entered into the rich text editor. 它返回输入到RTF编辑器中的文本。 Now, is there a way to pass this data using POST to my mvc controller and access it there? 现在,是否有一种方法可以使用POST将数据传递到我的mvc控制器并在那里访问它? (All this is being done in ASP.NET MVC 2 using C#) (所有这些操作都在ASP.NET MVC 2中使用C#完成)

You could send this value using AJAX. 您可以使用AJAX发送该值。 For example jQuery provides the .post() function: 例如, jQuery提供了.post()函数:

var val = tinyMCE.get('valueTextArea').getContent();
$.post('<%= Url.Action("foo") %>', { value: val }, function(result) {
    // TODO: handle the success
    alert('the value was successfully sent to the server');
});

and inside your controller action: 在控制器动作中:

[HttpPost]
public ActionResult Foo(string value)
{
    // Do something with the value
}

Now obviously because this is a RichText editor the value might contain dangerous characters and ASP.NET will reject them by throwing an exception. 现在显然是因为这是RichText编辑器,所以该值可能包含危险字符,并且ASP.NET将通过引发异常来拒绝它们。 To avoid this you could decorate your controller action with the [ValidateInput(false)] attribute: 为避免这种情况,您可以使用[ValidateInput(false)]属性装饰控制器动作:

[HttpPost]
[ValidateInput(false)]
public ActionResult Foo(string value)
{
    // Do something with the value
}

and if you are using ASP.NET 4.0 you should also add the following to your web.config: 如果您使用的是ASP.NET 4.0,则还应将以下内容添加到web.config中:

<httpRuntime requestValidationMode="2.0" />

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

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