ASP.NET MVC Razor - Sending data to the controller

25,146

Solution 1

if you are using strongly typed views then all you have to do is

 $.ajax({
        url: '@Url.Action( "SendEMail", "TournMaint")',
        data: {model:JSON.stringify(vInput)},
        type: 'POST',
   ...

and the controller looks like

[HttpPost]
public JsonResult SendEMail( CNameValue model )
{
    String prop = model.YourModelProperty; 

also you can use the form collection

 $.ajax({
        url: '@Url.Action( "SendEMail", "TournMaint")',
        data: {col :$("Formid").serialize()},
        type: 'POST',
   ...

and the controller looks like

[HttpPost]
public JsonResult SendEMail( FormCollection col )
{
    String prop = col.Get("FormFieldName"); 

Solution 2

The .post() syntax @ http://api.jquery.com/jQuery.post/ is nicer than .ajax imo. For example:

$(document).ready(function() 
{
    var model =
    {
        EmailAddress: 'Hello, World!'
    };

    var xhr = $.post('@Url.Action("SendEmail", "TournMaint")', model)
        .success(function(data)
        {
                    $('body').append('!success!');
                    $('body').append(JSON.stringify(data));
        })
        .error(function()
        {
                    $('body').append('!err!');
        })
        .complete(function()
        {
                    $('body').append('!complete!');
        });
    });

Your Controller could look like:

    public class MyModel { public string EmailAddress { get; set; } };

    [HttpPost]
    public JsonResult SendEmail(MyModel model)
    {
        return new JsonResult { Data = model };
    }

The page should show the object you sent to the server, and show you order of execution for the success/error/complete calls.

Share:
25,146
Scott Norberg
Author by

Scott Norberg

Updated on August 28, 2020

Comments

  • Scott Norberg
    Scott Norberg over 3 years

    There are all kinds of posts out there about getting the input fields off a form/div and sending them to your server side controller. What I am not clear on is how to accept the input at the controller.

    I have tried various methods:

    function SendEMail( vThis )
    {
        var vInput = $("#idEMailFields *").serializeArray();
    
        $.ajax({
            url: '@Url.Action( "SendEMail", "TournMaint")',
            data: JSON.stringify(vInput),
            type: 'POST',
            contentType: 'application/json; charset=utf-8;',
            dataType: 'json',
            success: function (response)
            {
                $("#idEMailResponse").html(response);
                return;
            },
            error: function( xhr, status, error )
            {
                debugger;
                var verr = xhr.status + "\r\n" + status + "\r\n" + error; 
                alert( verr );
            }   
        });
    }
    

    where the controller looks like:

    [HttpPost]
    public JsonResult SendEMail( CNameValue [] inputs )
    {
        String sView = "EMail messages queued"; 
        return Json( sView, JsonRequestBehavior.AllowGet );
    }
    

    The CNameValue class is my own creation since I didn't find a standard that would do the same thing. There should be a standard dictionary class that would pick the parameters up by name?? My question is how should this be done??

    The Second variation:

    function SendEMail( vThis )
    {
        var params = {};
        var v1 = $("#idEMailFields input[name=EMailAddressing], #idEMailFields input[type=hidden],#idEMailFields textarea");
        $(v1).each( function(index)
        {
            params[this.name]=this.value;
        });
        $.ajax({
            url: '@Url.Action( "SendEMail", "TournMaint")',
            data: JSON.stringify(params),
            type: 'POST',
            contentType: 'application/json; charset=utf-8;',
            dataType: 'json',
            success: function (response)
            {
                debugger;
                return;
            },
            error: function (x)
            {
                debugger;
                alert(x.status);
            }   
        });
    }
    

    Where the controller looks like:

    [HttpPost]
    public JsonResult SendEMail( Int32 TournamentId, String EMailText, String EMailAddressing )
    {
        String sView = "return something usefull";
        return Json( sView, JsonRequestBehavior.AllowGet );
    }
    

    This is not a bad way to move data to the sever but it is susceptible to changes in the razor markup causing the controller to blow. I know that you never get away from that problem but reducing the possibility is a thought.

    What is the best way to get screen data to the server side controller?