【问题标题】:Cannot update database entry and refresh dynamic WebGrid using jQuery - ASP.Net MVC无法使用 jQuery 更新数据库条目和刷新动态 WebGrid - ASP.Net MVC
【发布时间】:2014-01-28 12:32:16
【问题描述】:

我成功地根据 DropDownList 的选定项动态显示 WebGrid。如果我在 DropDownList 中选择另一个项目,我将看到一个不同的 WebGrid。在说明我接下来要做的事情之前,这里是我如何实现上述目标(在像你这样的人的大量帮助下)。

这是我的索引视图:

@model BarClients.Models.BarClientsViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Enter Client Information</h2>
<br />
<table>
    <tr>
        <th align="left">
            @Html.DisplayNameFor(model => model.BAR_Clients.ClientId)
        </th>
    </tr>
    <tr>
        <th valign="top">
            <div id="MeditechDropDown">
                @Html.DropDownListFor(model => model.BAR_Clients.ClientId, Model.MeditechClientID, "-- Select --", new { style = "width:170px" })
            </div>
        </th>
        <th>
            @{Html.RenderAction("EmailAddressGrid", "Home");}
        </th>
    </tr>
</table>

这是我的 EmailAddressGrid 视图:

@model BarClients.Models.BarClientsViewModel

@{
    WebGrid grid = null;
    if (Model.EmailAddressesOfChosenClient.Count<string>() != 0)
    {
        grid = new WebGrid(Model.EmailAddressesOfChosenClient, ajaxUpdateContainerId: "gridContent");
    }
}

<div id="gridContent">
@{ if (grid != null)
   {
       <table>
           <tr>
               <td>
               @grid.GetHtml(           
                columns: grid.Columns(
                grid.Column("Email Addresses", format: item => item)))
               </td>
               <td valign="top">
                   @Html.DisplayFor(model => model.InvoiceMode)
               </td>
           </tr>
       </table>     
   }
}
</div>

这是我用来根据 DropDownList (clientID) 的选择动态显示 WebGrid 的 jQuery:

jQuery(document).ready(function () {
    $("#MeditechDropDown").change(function () {
        var id = $(this).find(":selected").val()
        var clientID = { "clientID": id }
        $.ajax({
            url: "/Home/PopulateEmailAddressUI",
            data: JSON.stringify(clientID), // Send value of the drop down change of option
            type: 'POST',
            datatype: 'html',
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                $('#gridContent').html(response)
            }
        });
    });
});

这是返回异步 WebGrid 的控制器操作 PopulateEmailAddressUI:

[HttpPost]
public PartialViewResult PopulateEmailAddressUI(string clientID)
{
    _clientModel = InitialiseBarClientsModel();

    _clientModel.FindEmailAddresses(from client in eFormsDB.BAR_Clients where client.ClientId == clientID select client);

    return PartialView("~/Views/Home/EmailAddressGrid.cshtml", _clientModel);
}

到目前为止一切顺利。我的下一个任务是能够在编辑器上输入新的电子邮件地址。然后,我将点击“添加电子邮件”按钮,然后将其添加到由上面提到的 DropDownList 的当前选定项标识的数据库表记录中。为此,我在 WebGrid 的代码所在的“gridContent”div ID 中有一个额外的表:

<table>
    <tr>
        <th align="left">
            @Html.EditorFor(model => model.NewEmailAddress)
        </th>
        <th>
            @Html.DropDownListFor(model => model.BAR_Clients.InvoiceMode, Model.InvoiceOptions, new { style = "width:70px" })
        </th>
        <th>
            <div id="AddEmail">
                <button>Add Email</button>
            </div>
        </th>
    </tr>
    <tr>
        <th align="left">
            @Html.Raw("Enter New Email Address")
        </th>
    </tr>
</table>

我(不成功)尝试添加电子邮件地址并通过 jQuery 重新加载 WebGrid 如下:

jQuery(document).ready(function () {
    var addEmail = $('#AddEmail');
    addEmail.on('click', function () {
        var id = $("#MeditechDropDown").find(":selected").val()
        var clientID = { "clientID": id }
        $.ajax({
            url: "/Home/AddEmailAddress",
            data: JSON.stringify(clientID), // Send value of the drop down change of option
            type: 'POST',
            datatype: 'html',
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                $('#gridContent').html(response)
            }
        });
    });
});

我的控制器操作 AddEmailAddress 看起来像:

[HttpPost]
public PartialViewResult AddEmailAddress(string clientID)
{
    // Code to update database omitted

    return PartialView("~/Views/Home/EmailAddressGrid.cshtml", _clientModel);
}

基本上在输入新的电子邮件地址并单击“添加电子邮件”按钮后,什么都没有发生(控制器操作 AddEmailAddress 永远不会被调用)。我究竟做错了什么?可能会阻碍的事情是 AddEmail div ID 在 gridContent div ID 内。非常感谢您的任何指点。

【问题讨论】:

    标签: c# jquery webgrid


    【解决方案1】:

    为了让事情按我的预期工作,我需要一个看起来像这样的 jQuery 函数:

    jQuery(document).ready(function () {
        $("#MeditechDropDown").change(function () {
            var id = $(this).find(":selected").val()
            var clientID = { "clientID": id }
            $.ajax({
                url: "/Home/PopulateEmailAddressUI",
                data: JSON.stringify(clientID), // Send value of the drop down change of option
                type: 'POST',
                datatype: 'html',
                contentType: 'application/json; charset=utf-8',
                success: function (response) {
                    $('#gridContent').html(response)
                    $('button').click(function () {
                        var email = $("#NewEmailAddress").val()
                        var invoice = $("#InvoiceDropDown").find(":selected").val()
                        var emailInfo =
                        {
                            "clientID": id,
                            "emailAddress": email,
                            "invoiceMode": invoice
                        };
                        $.ajax({
                            url: "/Home/AddEmailAddress",
                            data: JSON.stringify(emailInfo),
                            type: 'POST',
                            contentType: 'application/json; charset=utf-8',
                            success: function (response) {
                                $('#gridContent').html(response)
                            }
                        });
                    })
                }
            });
        })
    });
    

    我的 EmailAddressGrid 视图看起来像:

    @model BarClients.Models.BarClientsViewModel
    
    @{
        WebGrid grid = null;
        if (Model.EmailAddressesOfChosenClient.Count<string>() != 0)
        {
            grid = new WebGrid(Model.EmailAddressesOfChosenClient, ajaxUpdateContainerId: "gridContent");
        }
    }
    
    <div id="gridContent">
    @{ if (grid != null)
       {
           <table>
               <tr>
                   <td>
                       @grid.GetHtml(
                tableStyle: "webgrid-table",
                headerStyle: "webgrid-header",
                footerStyle: "webgrid-footer",
                alternatingRowStyle: "webgrid-alternating-row",
                selectedRowStyle: "webgrid-selected-row",
                rowStyle: "webgrid-row-style",
                mode: WebGridPagerModes.All,
    
                columns: grid.Columns(
                grid.Column("Email Addresses", format: item => item)))
                   </td>
                   <td valign="top">
                       @Html.DisplayFor(model => model.InvoiceMode)
                   </td>
               </tr>
           </table>
    
          <br />
          <table>
              <tr>
                  <th align="left">
                      @Html.TextBoxFor(model => model.NewEmailAddress)
                  </th>
                  <th>
                      <div id="InvoiceDropDown">
                          @Html.DropDownListFor(model => model.BAR_Clients.InvoiceMode, Model.InvoiceOptions, new { style = "width:70px" })
                      </div>
                  </th>
                  <th>
                      <button>Add Email</button>
                  </th>
              </tr>
              <tr>
                  <th align="left">
                      @Html.Raw("Enter New Email Address")
                  </th>
              </tr>
          </table>     
       }
    }
    </div>
    

    我的模型类看起来像:

    public class BarClientsViewModel
    {
        private List<string> _clientID;
        private List<string> _emailAddresses;
    
        public BAR_Clients BAR_Clients;
        public veForms_BAR_Clients veForms_BAR_Clients;
        public string InvoiceMode;
    
        [EmailFormatVerification]
        public string NewEmailAddress;
    
        public Exceptions Exceptions;
    
        public BarClientsViewModel(IEnumerable<veForms_BAR_Clients> meditechClients)
        {
            _clientID = new List<string>();
            foreach(veForms_BAR_Clients client in meditechClients)
            {
                _clientID.Add(client.Number);
            }
    
            _emailAddresses = new List<string>();
        }
    
        public void FindEmailAddresses(IEnumerable<BAR_Clients> barClients)
        {
            string emailAddressLine = "";
            foreach(BAR_Clients client in barClients)   // There will only be one client here
            {
                emailAddressLine = client.EmailAddress;
                InvoiceMode = client.InvoiceMode;
            }          
    
            string[] temp = emailAddressLine.Split(';');
            _emailAddresses = new List<string>();
            _emailAddresses = temp.ToList();
        }
    
        public string AddEmail(IEnumerable<BAR_Clients> barClients, string emailAddress)
        {
            string emailAddressLine = "";
            foreach (BAR_Clients client in barClients)   // There will only be one client here
            {
                emailAddressLine = client.EmailAddress;
                emailAddressLine = String.Format("{0};{1}", emailAddressLine, emailAddress);
            }
    
            return emailAddressLine;
        }
    
        public IEnumerable<SelectListItem> MeditechClientID
        {
            get { return new SelectList(_clientID); }
        }
    
        public IEnumerable<String> EmailAddressesOfChosenClient
        {
            get { return _emailAddresses; }
        }
    
        public IEnumerable<SelectListItem> InvoiceOptions
        {
            get { return new SelectList(new List<string>() { "PRINT", "EMAIL", "BOTH" }); }
        }
    }
    

    我的两个EF生成的类如下:

    public partial class BAR_Clients
    {
        public string ClientId { get; set; }
        public string EmailAddress { get; set; }
        public string InvoiceMode { get; set; }
    }
    

    public partial class veForms_BAR_Clients
    {
        public string SourceID { get; set; }
        public string ClientID { get; set; }
        public string Number { get; set; }
        public string Name { get; set; }
    }
    

    我的相关控制器动作方法如下:

    public ViewResult Index()
    {
        _clientModel = InitialiseBarClientsModel();
        return View(_clientModel);
    }
    
    [HttpPost]
    public PartialViewResult PopulateEmailAddressUI(string clientID)
    {
        _clientModel = InitialiseBarClientsModel();
    
        _clientModel.FindEmailAddresses(from client in eFormsDB.BAR_Clients where client.ClientId == clientID select client);
    
        return PartialView("~/Views/Home/EmailAddressGrid.cshtml", _clientModel);
    }
    
    public PartialViewResult EmailAddressGrid()
    {
        _clientModel = InitialiseBarClientsModel();
        return PartialView("~/Views/Home/EmailAddressGrid.cshtml", _clientModel);
    }
    
    [HttpPost]
    public PartialViewResult AddEmailAddress(EmailInfo emailInfo)
    {
        _clientModel = InitialiseBarClientsModel();
    
        string updatedEmail = _clientModel.AddEmail(from client in eFormsDB.BAR_Clients where client.ClientId == emailInfo.clientID select client, emailInfo.emailAddress);
    
        var clientToUpdate = eFormsDB.BAR_Clients.Find(emailInfo.clientID);
    
        try
        {
            eFormsDB.Entry(clientToUpdate).Member("EmailAddress").CurrentValue = updatedEmail;
            eFormsDB.Entry(clientToUpdate).Member("InvoiceMode").CurrentValue = emailInfo.invoiceMode;
    
            eFormsDB.SaveChanges();
        }
        catch (Exception)
        {
            throw new Exception("General Exception occurred while saving to database");
        }
    
        _clientModel.FindEmailAddresses(from client in eFormsDB.BAR_Clients where client.ClientId == emailInfo.clientID select client);
    
        return PartialView("~/Views/Home/EmailAddressGrid.cshtml", _clientModel);
    }
    
    private BarClientsViewModel InitialiseBarClientsModel()
    {
        BarClientsViewModel clientModel = new BarClientsViewModel(from meditech in meditechDB.veForms_BAR_Clients select meditech);
    
        return clientModel;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 2014-11-10
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多