mvc вызов бритвы jquery модальный всплывающий скрипт из контроллера

0

Я пытаюсь отобразить модальное всплывающее окно jquery на событии httppost в контроллере, что-то вроде RegisterClientScript в веб-формах. В _layout.cshtml у меня есть следующее:

 <script>
            $(function () {
                $("#dialog-modal").dialog({
                    autoOpen: false,
                    height: 140,
                    modal: true
                });
            });
        </script> 

На мой взгляд, у меня есть следующее:

@{
    ViewBag.Title = "Add New Record";
}

<h2>Add New Record</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <p>Agents @Html.DropDownList("Agents", String.Empty)&nbsp;&nbsp; <input type="submit" name="Get Agent" value="Get Agent" title="Get Agent" id="btnGetAgent" /></p>
        <legend>Entries</legend> 
       <div class="editor-label">
           First Name
        </div>
        <div class="editor-field">            
           @Html.TextBox("FirstName", (string)ViewBag.FirstName)
        </div>
               <div class="editor-label">
           Last Name
        </div>
        <div class="editor-field">            
           @Html.TextBox("LastName", (string)ViewBag.LastName)
        </div>
          <div class="editor-label">
           Address
        </div>
        <div class="editor-field">            
           @Html.TextBox("Address", (string)ViewBag.Address)
        </div>
         <div class="editor-label">
           City/State/Zip
        </div>
         <div class="editor-field">            
           @Html.TextBox("City", (string)ViewBag.City, new { style="width:180px" }) @Html.TextBox("Zip", (string)ViewBag.Zip, new { style="width:60px" })
        </div>
         <div class="editor-label">
           Business#
        </div>
        <div class="editor-field">            
           @Html.TextBox("Business", (string)ViewBag.Business)
        </div>
         <div class="editor-label">
           Mobile#
        </div>
        <div class="editor-field">            
           @Html.TextBox("Mobile", (string)ViewBag.Mobile)
        </div>
         <div class="editor-label">
           Fax#
        </div>
        <div class="editor-field">            
           @Html.TextBox("Fax", (string)ViewBag.Fax)
        </div>
           <div class="editor-label">
          Email
        </div>
        <div class="editor-field">            
           @Html.TextBox("Email", (string)ViewBag.Email)
        </div>        
          <div class="editor-label">
          Position
        </div>      
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

    <div id="dialog-modal" title="Confirmation">
    <p>ViewBag.Confirmation</p>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

 The dialog-modal div should be displayed on postback in jquery modal window along with the data.

контроллер:

[InitializeSimpleMembership]
[HttpPost]
public ActionResult AddNewRecord(int? AgentID, FormCollection collection)
{
    if (collection["FirstName"].ToString() != string.Empty)
    {
        Agents agent = new Agents();
        agent.A_FirstName = collection["FirstName"].ToString();
        agent.A_LastName = collection["LastName"].ToString();
        agent.A_Address = collection["Address"].ToString();
        agent.A_City = collection["City"].ToString();
        agent.A_State = collection["State"].ToString();
        agent.A_ZipCode = collection["Zip"].ToString();
        agent.A_Phone = collection["Business"].ToString();
        agent.A_FAX = collection["Fax"].ToString();
        agent.Email = collection["Email"].ToString();
        _fe.Agents.Add(agent);
        _fe.SaveChanges();             
        string username = agent.A_FirstName + agent.A_LastName;
        string password = GenerateRandomPassword(8);
        WebSecurity.CreateUserAndAccount(username, password);
        ViewBag.Confirmation = "Record Entered";
        AppHelper.SendWelcomeEmail("", "", username, password);
        AppHelper.SendWelcomeEmailAdminNotification("", "", agent.A_FirstName, agent.A_LastName, true, agent.Email, agent.AgentID, username);
    }            
    var modelAgent = _fe.Agents.Take(10);
    SelectList sl = new SelectList((from s in _aa.Agents.ToList() select new { COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME }), "COUNTER", "FullName", null);
    ViewBag.Agents = sl;          

    if (AgentID != null && AgentID != 0)
    {                        
       var modelAgentFilter = from s in _aa.Agents
                               where s.AgentID == AgentID
                               select s;
        if (modelAgentFilter != null)
        {
            foreach (var property in modelAgentFilter)
            {
                ViewBag.FirstName = property.FIRSTNAME;
                ViewBag.LastName = property.LASTNAME;
                ViewBag.Address = property.ADDRESS;
                ViewBag.State = property.STATE;
                ViewBag.City = property.CITY;
                ViewBag.Zip = property.ZIPCODE;
                ViewBag.Business = property.BUSPHONE;
                ViewBag.Mobile = property.HOMEPHONE;
                ViewBag.Fax = property.FAXPHONE;
                ViewBag.Email = property.Email;                       
            }            
        }
        return View(modelAgentFilter);                              
    }
    return View();    
}

Теперь вы можете увидеть синтаксис webforms, но, поскольку я перехожу из веб-форм в mvc, пожалуйста, извините меня за этот подход. Как вы можете видеть, когда я возвращаю модель, я хочу также включить некоторый код, чтобы вызвать отображение модального всплывающего окна. Пожалуйста, дайте мне знать, какой подход будет лучшим. Большое спасибо заранее, Laziale

  • 0
    Почему вы хотите, чтобы всплывающее окно появлялось после сообщения?
  • 0
    @Jared подтверждение, что действие успешно выполнено. Спасибо
Теги:
razor
asp.net-mvc
asp.net-mvc-4

1 ответ

0
Лучший ответ

Я не уверен, что правильно вас понимаю. Если новый пользователь был успешно создан, вы получаете AgentID. Поэтому вы можете попробовать что-то вроде этого:

   //Delete "autoOpen: false" option from your dialog     

   @if(Model.AgentID != null)
     {
       <script>
            $(function () {
                $("#dialog-modal").dialog({
                    height: 140,
                    modal: true
                });
            });
        </script> 
    }
  • 0
    arghhh, инфраструктура MVC настолько проста ... по сравнению с веб-формами, которые сделали то, что нужно. Спасибо
  • 0
    @Laziale, нужно помнить одну вещь: это будет работать, только если вы не используете один и тот же вид для создания / редактирования. Если вы используете тот же вид для редактирования, ваша модель будет иметь AgentID, и ваше сообщение будет отображаться при загрузке представления редактирования.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню