asp.net-mvc 使用 Jquery/Ajax 将模型传递给控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33947882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:30:34  来源:igfitidea点击:

Pass Model To Controller using Jquery/Ajax

asp.net-mvcasp.net-coreasp.net-core-mvc

提问by Reafidy

I am trying to pass my model to a controller using JQuery/Ajax, I'm not sure how to do this correctly. So far I have tried using Url.Actionbut the model is blank.

我正在尝试使用 JQuery/Ajax 将我的模型传递给控制器​​,我不确定如何正确执行此操作。到目前为止,我已经尝试使用,Url.Action但模型是空白的。

Note: none of the duplicate threads on stackoverflow seem to address using ASP.NET 5 MVC 6.

注意:stackoverflow 上的重复线程似乎都没有使用 ASP.NET 5 MVC 6 解决。

View:

看法:

$("#inpDateCompleted").change(function () {
        var url = '@(Url.Action("IndexPartial", "DashBoard", Model, null))';
        $("#DailyInvoiceItems").load(url);
});

Controller:

控制器:

 [HttpGet]
 public PartialViewResult IndexPartial(DashBoardViewModel m)
 {
      // Do stuff with my model
      return PartialView("_IndexPartial");
 }

回答by Shyju

Looks like your IndexPartialaction method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPostaction method and use jQuery postto post data to that. GET has limitation on the query string value.

看起来您的IndexPartial操作方法有一个参数,它是一个复杂的对象。如果您要传递大量数据(复杂对象),最好将您的操作方法转换为HttpPost操作方法并使用 jQuerypost将数据发布到该方法。GET 对查询字符串值有限制。

[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
   //May be you want to pass the posted model to the parial view?
   return PartialView("_IndexPartial");
}

Your script should be

你的脚本应该是

var url = "@Url.Action("IndexPartial","YourControllerName")";

var model = { Name :"Shyju", Location:"Detroit"};

$.post(url, model, function(res){
   //res contains the markup returned by the partial view
   //You probably want to set that to some Div.
   $("#SomeDivToShowTheResult").html(res);
});

Assuming Nameand Locationare properties of your DashboardViewModelclass and SomeDivToShowTheResultis the id of a div in your page where you want to load the content coming from the partialview.

假设NameLocation是您的DashboardViewModel类的属性,并且SomeDivToShowTheResult是您要加载来自局部视图的内容的页面中 div 的 id。

Sending complex objects?

发送复杂的对象?

You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class

如果需要,您可以在 js 中构建更复杂的对象。只要您的结构与 viewmodel 类匹配,模型绑定就会起作用

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","Stackoverflow"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});

For the above js model to be transformed to your method parameter, Your View Model should be like this.

上面的js模型要转换成你的方法参数,你的视图模型应该是这样的。

public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}

And in your action method, specify [FromBody]

在您的操作方法中,指定 [FromBody]

[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}

回答by kavita sharma

Use the following JS:

使用以下JS:

$(document).ready(function () {
    $("#btnsubmit").click(function () {

             $.ajax({
                 type: "POST",
                 url: '/Plan/PlanManage',     //your action
                 data: $('#PlanForm').serialize(),   //your form name.it takes all the values of model               
                 dataType: 'json',
                 success: function (result) {
                     console.log(result);
                 }
             })
        return false;
    });
});

and the following code on your controller:

以及控制器上的以下代码:

[HttpPost]
public string PlanManage(Plan objplan)  //model plan
{
}

回答by Julius Depulla

//C# class

public class DashBoardViewModel 
{
    public int Id { get; set;} 
    public decimal TotalSales { get; set;} 
    public string Url { get; set;} 
     public string MyDate{ get; set;} 
}

//JavaScript file
//Create dashboard.js file
$(document).ready(function () {

    // See the html on the View below
    $('.dashboardUrl').on('click', function(){
        var url = $(this).attr("href"); 
    });

    $("#inpDateCompleted").change(function () {   

        // Construct your view model to send to the controller
        // Pass viewModel to ajax function 

        // Date
        var myDate = $('.myDate').val();

        // IF YOU USE @Html.EditorFor(), the myDate is as below
        var myDate = $('#MyDate').val();
        var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };


        $.ajax({
            type: 'GET',
            dataType: 'json',
            cache: false,
            url: '/Dashboard/IndexPartial',
            data: viewModel ,
            success: function (data, textStatus, jqXHR) {
                //Do Stuff 
                $("#DailyInvoiceItems").html(data.Id);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //Do Stuff or Nothing
            }
        });

    });
});

//ASP.NET 5 MVC 6 Controller
public class DashboardController {

    [HttpGet]
    public IActionResult IndexPartial(DashBoardViewModel viewModel )
    {
        // Do stuff with my model
        var model = new DashBoardViewModel {  Id = 23 /* Some more results here*/ };
        return Json(model);
    }
}

// MVC View 
// Include jQuerylibrary
// Include dashboard.js 
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically 

<div>
    <a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
    <input class="myDate" type="text"/>
//OR
   @Html.EditorFor(model => model.MyDate) 
</div>

回答by Rob

As suggested in other answers it's probably easiest to "POST" the form data to the controller. If you need to pass an entire Model/Form you can easily do this with serialize()e.g.

正如其他答案中所建议的那样,将表单数据“发布”到控制器可能是最简单的。如果您需要传递整个模型/表单,您可以使用serialize()例如

$('#myform').on('submit', function(e){
    e.preventDefault();

    var formData = $(this).serialize();

    $.post('/student/update', formData, function(response){
         //Do something with response
    });
});

So your controller could have a view model as the param e.g.

所以你的控制器可以有一个视图模型作为参数,例如

 [HttpPost]
 public JsonResult Update(StudentViewModel studentViewModel)
 {}

Alternatively if you just want to post some specific values you can do:

或者,如果您只想发布一些特定值,您可以执行以下操作:

$('#myform').on('submit', function(e){
    e.preventDefault();

    var studentId = $(this).find('#Student_StudentId');
    var isActive = $(this).find('#Student_IsActive');

    $.post('/my/url', {studentId : studentId, isActive : isActive}, function(response){
         //Do something with response
    });
});

With a controller like:

使用控制器,例如:

     [HttpPost]
     public JsonResult Update(int studentId, bool isActive)
     {}