使用Jquery / Ajax将模型传递给Controller

时间:2015-11-26 22:32:19

标签: asp.net-mvc asp.net-core asp.net-core-mvc

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

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

查看:

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

控制器:

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

4 个答案:

答案 0 :(得分:54)

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

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

您的脚本应该是

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

假设NameLocationDashboardViewModel类的属性,SomeDivToShowTheResult是您网页中div的ID,您要加载来自partialview。

发送复杂对象?

如果需要,可以在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);
});

要将上述js模型转换为您的方法参数,您的视图模型应该是这样的。

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

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

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

答案 1 :(得分:8)

使用以下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;
    });
});

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

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

答案 2 :(得分:6)

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

答案 3 :(得分:2)

正如在其他答案中所建议的那样,它可能是最简单的&#34; POST&#34;表格数据到控制器。如果您需要传递整个模型/表单,可以使用serialize()例如

轻松完成
$('#myform').on('submit', function(e){
    e.preventDefault();

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

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

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

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

或者,如果您只想发布一些特定值,您可以这样做:

$('#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
    });
});

使用如下控制器:

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