ASP.NET MVC Razor - 將數據發送到控制器

[英]ASP.NET MVC Razor - Sending data to the controller


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.

有各種各樣的帖子關於從表單/ div獲取輸入字段並將它們發送到服務器端控制器。我不清楚的是如何接受控制器的輸入。

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??

CNameValue類是我自己創建的,因為我沒有找到可以做同樣事情的標准。應該有一個標准的字典類,可以按名稱選擇參數?我的問題是如何做到這一點?

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?

將屏幕數據傳送到服務器端控制器的最佳方法是什么?

2 个解决方案

#1


8  

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"); 

#2


2  

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

.post()語法@ http://api.jquery.com/jQuery.post/比.ajax imo好。例如:

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

該頁面應顯示您發送到服務器的對象,並顯示成功/錯誤/完成調用的執行順序。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/09/17/7252fb870a71d13835c64818dfe566cf.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com