开发者

Passing value from javascript to mvc controller

开发者 https://www.devze.com 2023-02-08 07:16 出处:网络
I am using tinyMCE (a rich text editor in js). Currently, I have a function as such: function GetEditorValue() {

I am using tinyMCE (a rich text editor in js). Currently, I have a function as such:

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

    }

which returns the text tha开发者_JS百科t was entered into the rich text editor. Now, is there a way to pass this data using POST to my mvc controller and access it there? (All this is being done in ASP.NET MVC 2 using C#)


You could send this value using AJAX. For example jQuery provides the .post() function:

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. To avoid this you could decorate your controller action with the [ValidateInput(false)] attribute:

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

<httpRuntime requestValidationMode="2.0" />
0

精彩评论

暂无评论...
验证码 换一张
取 消