简体   繁体   中英

Passing value from javascript to mvc controller

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 that 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" />

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