簡體   English   中英

如何在 ASP.NET Razor 視圖中使用 jQuery 將模型發送回 ASP.NET 控制器

[英]How send the model back to an ASP.NET controller using jQuery in a ASP.NET Razor view

我有一個接受數據的 Razor 視圖。 我正在使用表單,但我沒有使用 post 方法,因為我想首先提示用戶保存。 所以我有保存按鈕來觸發一個 jQuery 函數,然后我觸發控制器的保存方法。 在其他應用程序中,我會在 Html.BeginForm() 中定義 Post save 方法,它會觸發相應的控制器方法。 但是因為我想先運行一個模態,所以我想自己觸發那個方法。

jQuery 彈出一個模式進行確認,接受后,我嘗試觸發對控制器的 save 方法的調用。

我在控制台中收到“模型未定義”。 但是,我可以在視圖中的任何 html 幫助程序中很好地引用模型。

我如何在這個級別獲得對該模型的引用 - 在 jQuery 中?

好像看到了:

在此處輸入圖片說明

$.post("UserProfile/ProcessSaveUserProfile", { userProfileForMaintVM: Model });

Razor 視圖(簡化):

  @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...           
    }

您需要創建一個模型,當您執行 ajax POST 時,這些屬性將被綁定。

  1. 但首先,我相信您需要在表單中放置一個 ID/主鍵字段。
@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>
  }
  1. 創建一個模型,這些屬性將綁定到;
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;}
}
  1. 在您的按鈕單擊中使用它,不要忘記更改腳本上輸入字段的 ID;
$(".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");
      }
   });
});
  1. 然后在您的控制器操作中,使用 ReceiveModel 作為參數。
[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();          
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM