如何在ASP.NET Razor视图中使用jQuery将模型发送回ASP.NET控制器

如何在ASP.NET Razor视图中使用jQuery将模型发送回ASP.NET控制器,jquery,asp.net-mvc,razor,Jquery,Asp.net Mvc,Razor,我有一个接受数据的Razor视图。我使用的是表单,但我没有使用post方法,因为我想首先提示用户保存。因此,我使用save按钮启动jQuery函数,然后启动控制器的save方法。在其他应用程序中,我会在Html.BeginForm()中定义Post save方法,该方法触发相应的控制器方法。但由于我想先运行一个模态,我想自己启动这个方法 jQuery弹出一个模式进行确认,在接受后,我尝试调用控制器的save方法 我在控制台中得到“模型未定义”。但是,我可以在视图中的任何html帮助程序中很好地引

我有一个接受数据的Razor视图。我使用的是表单,但我没有使用post方法,因为我想首先提示用户保存。因此,我使用save按钮启动jQuery函数,然后启动控制器的save方法。在其他应用程序中,我会在Html.BeginForm()中定义Post save方法,该方法触发相应的控制器方法。但由于我想先运行一个模态,我想自己启动这个方法

jQuery弹出一个模式进行确认,在接受后,我尝试调用控制器的save方法

我在控制台中得到“模型未定义”。但是,我可以在视图中的任何html帮助程序中很好地引用该模型

在jQuery中,如何在这个级别获得对该模型的引用

似乎看到了:

剃须刀视图(简化):

@model GbngWebClient.Models.userprofileformainvm
@使用(Html.BeginForm())
{
@ValidationSummary(true,“请修复以下错误”)
@LabelFor(model=>model.UserProfileSingleVM.Email)
@Html.TextBoxFor(model=>model.UserProfileSingleVM.Email,新的{@class=“form control”})
@Html.ValidationMessageFor(model=>model.UserProfileSingleVM.Email,“,新的{@class=“text danger”})
@LabelFor(model=>model.UserProfileSingleVM.WantEmailNotificationsSwitch)
@CheckBoxFor(model=>model.UserProfileSingleVM.wantemailnotificationswitch,new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.UserProfileSingleVM.WantEmailNotificationsSwitch,“,new{@class=“text danger”})
@LabelFor(model=>model.UserProfileSingleVM.City)
@TextBoxFor(model=>model.UserProfileSingleVM.City,新的{@class=“form control”})
@Html.ValidationMessageFor(model=>model.UserProfileSingleVM.City,“,新{@class=“text danger”})
}
@Html.AntiForgeryToken()
函数ConfirmSaveProfile(){
$(`
是否确实要保存更改?
对
不
`).附于(“主体”);
$(“#myModal6”).modal({
背景:“静态”,
键盘:错误
});
$(“.btn-yes6”)。单击(函数(){
$(“#myModal6”).modal(“隐藏”);
//我不想回电话。
$.post(“UserProfile/ProcessSaveUserProfile”,{userprofileformainvm:Model});
});
$(“.btn-no6”)。单击(函数(){
$(“#myModal6”).modal(“隐藏”);
});
$(“#myModal6”).on('hidden.bs.modal',function(){
$(“#myModal6”).remove();
});
}
控制器方法(简化):

[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务进程SaveUserProfile(UserProfileFormainVM UserProfileFormainVM)
{
调用web api的代码。。。
}

您需要创建一个模型,当您发布ajax文章时,这些属性将被绑定到该模型中

  • 但首先,我认为您需要在表单中输入一个ID/主键字段
  • 在您的按钮单击中使用此选项,不要忘记更改脚本上输入字段的ID
  • 然后在控制器操作中,使用ReceiveModel作为参数
  • [HttpPost]
    [ValidateAntiForgeryToken]
    公共异步任务进程SaveUserProfile(ReceiveModel模型)
    {
    //替换为id属性
    userprofileformainvm uvm=db.userprofileformainvm.FirstOrDefault(m=>m.Id==model.Id);
    //分配新属性
    uvm.UserProfileSingleVM.Email=model.Email;
    uvm.UserProfileSingleVM.WantEmailNotificationsSwitch=model.WantEmailNotificationsSwitch;
    uvm.UserProfileSingleVM.City=model.City;
    //调用web api,然后传递uvm
    db.SaveChanges();
    }
    
    请包含您的表单代码。实际上,我需要查看html帮助程序,我不确定.serialize()是否能够正确映射它们。我在那里添加了更多内容。注意:它工作正常,因为它显示模型数据。就在我存钱的时候。在jQuery中,我引用模型。但它在运行时声明“模型未定义”。在其他应用程序中,我会在Html.BeginForm()中定义Post方法,该方法触发相应的控制器方法。。但是,由于我想先运行一个模型,然后我将自己启动该方法。我已经在视图中有了一个模型。我在模型中有大约35个下拉列表,以及大约25个主要字段。为什么我必须创建另一个?所有这些都连接到htmlhelpers并显示得很好。他们不受我已有的模型约束吗?。我可以很好地编辑和选择数据。我有一篇关于AJAX的帖子。只是在jQuery中找不到模型。我就是不明白为什么。我尝试过:var datafromform=$(“#Model”).val();我没有定义。我只看到了3个字段,所以我的答案就在那里。您可以做的是在
    var数据
    分配期间,将您的所有属性放在那里<代码>$(“Model.val()
    或对
    @Model
    的任何引用都不会起作用,因为
    @Model
    值在您提交之前是固定的。它们不像angular或客户端框架那样绑定,您所做的任何更改都会自动反映出来。简单测试:使用模型和属性,我得到“未定义”。var whoIAmDescrModel=$(“#Model.UserProfileSingleVM.WhoIAmDescr”).val();现在使用元素名:var WhoIAmDescr=$(“#UserProfileSingleVM_WhoIAmDescr”).val();我得到了它的实际值。因此我根本无法引用该模型。
    $.post("UserProfile/ProcessSaveUserProfile", { userProfileForMaintVM: Model });
    
      @model GbngWebClient.Models.UserProfileForMaintVM
    
      @using (Html.BeginForm())
      {
        @Html.ValidationSummary(true, "Please fix the following errors.")
            <div class="row">
                <div class="col-md-3">
                    @Html.LabelFor(model => model.UserProfileSingleVM.Email)
                    @Html.TextBoxFor(model => model.UserProfileSingleVM.Email, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.UserProfileSingleVM.Email, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-3">
                    @Html.LabelFor(model => model.UserProfileSingleVM.WantEmailNotificationsSwitch)
                    @Html.CheckBoxFor(model => model.UserProfileSingleVM.WantEmailNotificationsSwitch, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.UserProfileSingleVM.WantEmailNotificationsSwitch, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-3">
                    @Html.LabelFor(model => model.UserProfileSingleVM.City)
                    @Html.TextBoxFor(model => model.UserProfileSingleVM.City, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.UserProfileSingleVM.City, "", new { @class = "text-danger" })
                </div>
            </div>
         </div>
      }
    
      @Html.AntiForgeryToken()
    
      <div class="panel-body">
         <div class="row">
             <div class="col-md-3">
              <a href='#' type="submit" class='btn btn-primary' 
      onclick=ConfirmSaveProfile();>Save</a>
             </div>
         </div>
     </div>
    
      function ConfirmSaveProfile() {
      $(`<div class="modal fade" id="myModal6" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                   <div class="modal-body" style="padding:10px;">
                   <h4 class="text-center">Are you sure you want to save your changes ?</h4>
                   <div class="text-center">
                       <a class="btn btn-info btn-yes6">Yes</a>
                       <a class="btn btn-default btn-no6">No</a>
                    </div>
                 </div>
             </div>
           </div>
        </div>`).appendTo('body');
    
         $("#myModal6").modal({
            backdrop: 'static',
            keyboard: false
        });
    
        $(".btn-yes6").click(function () {
            $("#myModal6").modal("hide");
    
            // Don't want a callback.
            $.post("UserProfile/ProcessSaveUserProfile", { userProfileForMaintVM: Model });
        });
    
        $(".btn-no6").click(function () {
            $("#myModal6").modal("hide");
        });
    
        $("#myModal6").on('hidden.bs.modal', function () {
            $("#myModal6").remove();
        });
    }
    
      [HttpPost]
      [ValidateAntiForgeryToken]
      public async Task<ActionResult> ProcessSaveUserProfile(UserProfileForMaintVM userProfileForMaintVM)
        {
           Code to call the web api...           
        }
    
    @using (Html.BeginForm())
      {
        // replace this with your primary key field
        @Html.HiddenFor(model=>model.Id)
    
        @Html.ValidationSummary(true, "Please fix the following errors.")
            <div class="row">
                <div class="col-md-3">
                    @Html.LabelFor(model => model.UserProfileSingleVM.Email)
                    @Html.TextBoxFor(model => model.UserProfileSingleVM.Email, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.UserProfileSingleVM.Email, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-3">
                    @Html.LabelFor(model => model.UserProfileSingleVM.WantEmailNotificationsSwitch)
                    @Html.CheckBoxFor(model => model.UserProfileSingleVM.WantEmailNotificationsSwitch, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.UserProfileSingleVM.WantEmailNotificationsSwitch, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-3">
                    @Html.LabelFor(model => model.UserProfileSingleVM.City)
                    @Html.TextBoxFor(model => model.UserProfileSingleVM.City, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.UserProfileSingleVM.City, "", new { @class = "text-danger" })
                </div>
            </div>
         </div>
      }
    
    public class ReceiveModel{
       // replace this with data type and name of your primary key field
       public int Id {get;set;}
    
       // replace data type if incorrect
       public string Email {get;set;}
       public bool WantEmailNotificationsSwitch {get;set;}
       public string City {get;set;}
    }
    
    $(".btn-yes6").click(function () {
       // replace the selectors below with the id attribute of your input fields
       // replace Id with your primary key field
    
       var data = {
          Id: $("#Model.Id").val(),
          Email: $("#Model.UserProfileSingleVM.Email").val(),
          WantEmailNotificationsSwitch: $("#Model.UserProfileSingleVM.WantEmailNotificationsSwitch").val(),
          City: $("#Model.UserProfileSingleVM.City").val()
       };
    
       $.ajax({
          url: 'UserProfile/ProcessSaveUserProfile',
          type: 'POST',
          data: data,
          contentType: 'application/json; charset=utf-8',
          success: function (data) {
             // ...
          },
          error: function () {
             alert("error");
          }
       });
    });
    
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ProcessSaveUserProfile(ReceiveModel model)
    {
       // replace with id property
       UserProfileForMaintVM uvm = db.UserProfileForMaintVM.FirstOrDefault(m=>m.Id==model.Id);
    
       // assign new properties
       uvm.UserProfileSingleVM.Email = model.Email;
       uvm.UserProfileSingleVM.WantEmailNotificationsSwitch = model.WantEmailNotificationsSwitch;
       uvm.UserProfileSingleVM.City = model.City;
    
       // call your web api then pass uvm 
       db.SaveChanges();          
    }