MVC 3, используя dropdownlist и ajax, чтобы получить новую модель - PullRequest
1 голос
/ 12 октября 2011

У меня есть частичное представление, что при первом открытии имеет пустую модель.Он состоит из выпадающего списка, текстовой области и 2 текстовых полей.Когда пользователь выбирает значение из выпадающего меню, я хочу вернуться и получить модель со значениями и заполнить мое представление.Как это сделать?

вот мое первоначальное действие, которое загружает частичное представление в элемент управления разделителя:

Function SelectDisclosures() As ActionResult
        Return PartialView()
End Function

Представление:

<%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl(Of Community_Portal_Admin.Disclosure)" %>
<script type="text/javascript">
    function onDropDownListChange(e) {
        var editor;
        if (e.value != '') {
            $.post('<%:Url.Action("_SelectDisclosures","SiteTerms") %>', { id: e.value },
            function (data) {
                if (data != "Error") {
                    editor = $('#DisclosureHTML').data('tEditor');
                    editor.value(data);
                } else {
                    return false;
                }
            });
        }
    }
</script>
<% Using Html.BeginForm("UpdateDisclosure", "SiteTerms", FormMethod.Post, New With {.id = "DisclosuresForm"})%>
    <fieldset>
        <div class="gridFrame">
            <br />
            <%: Html.Label("WebRole", "Role: ")%>
            <%: Html.Telerik().DropDownList() _
                                .Name("WebRoles") _
                                .ClientEvents(Function(e) e.OnChange("onDropDownListChange")) _
                                .DataBinding(Function(binding) binding.Ajax().Select("_SelectWebRoles", "SiteTerms"))
            %>
            <br /><br />        
            <%: Html.Telerik().Editor() _
                                .Name("DisclosureHTML") _
                                .HtmlAttributes(New With {.id = "DisclosureHTML", .style = "height:275px;"})
            %>
            <br />
            <%: Html.TextBoxFor(Function(m) m.ID, New With {.id = "hidID"})%>
            <%: Html.TextBoxFor(Function(m) m.WebRoleID, New With {.id = "hidWebRoleID"})%>
            <%: Html.TextAreaFor(Function(m) m.DisclosureHTML, New With {.id = "hidDisclosureHTML"})%>
            <div class="smallFrameLeft">        
                <%: Html.ActionLink("Cancel", "Index", "Configuration", Nothing, New With {.class = "t-button", .Style = "font-size:12px;"})%>
            </div>
            <div class="smallFrameRight">
                <input type="submit" name="Save" value="Save" class="t-button" />       
            </div>
        </div>
    </fieldset>
<%--   <script type="text/javascript">
       $(".smallFrameRight").click(function (e) {
           var form = $(this).closest("form");
           e.preventDefault();
           $.blockUI({ message: '<div style="text-align: top;"><img src="Images/loading.gif" /><h3> Saving...</h3></div>' });
           $.post(form.attr("action"), form.serialize(), function (data) {
           });
           setTimeout($.unblockUI, 400);
       });
    </script>--%>
<% End Using%>

Действие, котороезаполняет выпадающий список:

Function _SelectWebRoles() As ActionResult
    Dim l As IList(Of WebRole) = Nothing
    Try
        l = WebRoleRepository.All()
        Return New JsonResult With {.Data = New SelectList(l, "ID", "Name")}
    Catch ex As Exception
        TempData("ErrorMessage") = "There was a problem during page load: " & ex.Message & vbCrLf & vbCrLf & ex.StackTrace
        Return RedirectToAction("HttpError", "Error")
    Finally
        If Not l Is Nothing Then l = Nothing
    End Try
End Function

Это мое первоначальное действие, я просто возвращал только одно текстовое значение и устанавливал его в редакторе.Но я бы предпочел вернуть целую модель и позволить ей заполнить представление самостоятельно, так что я также смогу опубликовать всю модель обратно.

'Function GetDisclosure(ByVal id As Integer) As ActionResult
'    Dim setting As Disclosure = Nothing
'    Dim notice As String = String.Empty
'    Try
'        setting = DisclosureRepository.One(Function(d) d.WebRoleID = id)
'        If Not setting Is Nothing Then notice = HttpUtility.HtmlDecode(setting.DisclosureHTML)
'        Return Content(setting)
'    Catch ex As Exception
'        Return Content("Error")
'    Finally
'        If Not setting Is Nothing Then setting.Dispose() : setting = Nothing
'        notice = Nothing
'    End Try
'End Function

1 Ответ

0 голосов
/ 12 октября 2011

Я понял это сам, используя магию jQuery, вот вид:

<%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl(Of Community_Portal_Admin.Disclosure)" %>

<script type="text/javascript">

function onDropDownListChange(e) {

    var hid;
    var hrole;
    var editor;
    var arry = Array();

    hid = document.getElementById("hidID");
    hrole = document.getElementById("hidWebRoleID");
    editor = $('#DisclosureHTML').data('tEditor');

    if (e.value != '') {
        $.post('<%:Url.Action("GetDisclosure","SiteTerms") %>', { id: e.value },
        function (data) {
            if (data != "NotFound") {
                arry = data.split("|||");
                hid.value = arry[0];
                hrole.value = arry[1];
                editor.value(arry[2]);
            } else {
                hid.value = -1;
                hrole.value = e.value;
                editor.value('');
                return false;
            }
        });
    }
}

</script>

<% Using Html.BeginForm("UpdateDisclosure", "SiteTerms", FormMethod.Post, New With {.id = "DisclosuresForm"})%>
<fieldset>
    <div class="gridFrame">

        <br />
        <%: Html.Label("WebRole", "Role: ")%>
        <%: Html.Telerik().DropDownList() _
                            .Name("WebRoles") _
                            .ClientEvents(Function(e) e.OnChange("onDropDownListChange")) _
                            .DataBinding(Function(binding) binding.Ajax().Select("_SelectWebRoles", "SiteTerms"))
        %>

        <br />
        <br />

        <%: Html.Telerik().EditorFor(Function(m) m.DisclosureHTML) _
                            .Name("DisclosureHTML") _
                            .HtmlAttributes(New With {.id = "DisclosureHTML", .style = "height:275px;"})
        %>

        <br />

        <%: Html.HiddenFor(Function(m) m.ID, New With {.id = "hidID"})%>
        <%: Html.HiddenFor(Function(m) m.WebRoleID, New With {.id = "hidWebRoleID"})%>

        <div class="smallFrameLeft">        
            <%: Html.ActionLink("Cancel", "Index", "Configuration", Nothing, New With {.class = "t-button", .Style = "font-size:12px;"})%>
        </div>

        <div id="saveButton" class="smallFrameRight">
            <input type="submit" name="Save" value="Save" class="t-button" />       
        </div>

        <div id="deleteButton" class="smallFrameRight">
            <input type="submit" name="Delete" value="Delete" class="t-button" />       
        </div>

    </div>
</fieldset>

<script type="text/javascript">

   $("#saveButton").click(function (e) {
       var form = $(this).closest("form");

       e.preventDefault();

       $.blockUI({ message: '<div style="text-align: top;"><img src="Images/loading.gif" /><h3> Saving...</h3></div>' });
           $.post(form.attr("action"), form.serialize(), function (data) {
           });
       setTimeout($.unblockUI, 400);
   });

   $("#deleteButton").click(function (e) {
       e.preventDefault();

       var hid;
       var hrole;
       var editor;

       hid = document.getElementById("hidID");
       hrole = $('#WebRoles').data('tDropDownList').value();
       editor = $('#DisclosureHTML').data('tEditor');

       if (hrole != '') {
           $.blockUI({ message: '<div style="text-align: top;"><img src="Images/loading.gif" /><h3> Deleting...</h3></div>' });
           $.post('<%:Url.Action("DeleteDisclosure","SiteTerms") %>', { id: hrole },
                function (data) {
                    if (data != "Error") {
                        hid.value = -1;
                        editor.value('');
                    } else {
                        return false;
                    }
                });
           setTimeout($.unblockUI, 400);
        }
   });

</script>

<% End Using%>

Вот контроллер:

#Region "Disclosure"

    Function SelectDisclosures(ByVal model As Disclosure) As ActionResult

        Try
            ViewData.Model = model

            Return PartialView()

        Catch ex As Exception
            TempData("ErrorMessage") = "There was a problem during page load: " & ex.Message & vbCrLf & vbCrLf & ex.StackTrace
            Return RedirectToAction("HttpError", "Error")
        End Try

    End Function

    Function _SelectWebRoles() As ActionResult

        Dim l As IList(Of WebRole) = Nothing

        Try
            l = WebRoleRepository.All()

            Return New JsonResult With {.Data = New SelectList(l, "ID", "Name")}

        Catch ex As Exception
            TempData("ErrorMessage") = "There was a problem during page load: " & ex.Message & vbCrLf & vbCrLf & ex.StackTrace
            Return RedirectToAction("HttpError", "Error")
        Finally
            If Not l Is Nothing Then l = Nothing
        End Try

    End Function

    Function GetDisclosure(ByVal id As Integer) As ActionResult

        Dim setting As Disclosure = Nothing

        Try
            setting = DisclosureRepository.One(Function(d) d.WebRoleID = id)

            If Not setting Is Nothing Then setting.DisclosureHTML = HttpUtility.HtmlDecode(setting.DisclosureHTML)

            Return Content(setting.ID.ToString & "|||" & setting.WebRoleID.ToString & "|||" & setting.DisclosureHTML)

        Catch ex As Exception
            Return Content("NotFound")
        Finally
            If Not setting Is Nothing Then setting.Dispose() : setting = Nothing
        End Try

    End Function

    <HttpPost()> _
    Function UpdateDisclosure(ByVal setting As Disclosure) As ActionResult

        Try
            If setting.ID = -1 Then
                If TryUpdateModel(setting) Then
                    DisclosureRepository.Insert(setting)
                End If
            End If

            If TryUpdateModel(setting) Then
                DisclosureRepository.Update(setting)
            End If

            Return PartialView(setting)

        Catch ex As Exception
            TempData("ErrorMessage") = "There was a problem during update: " & ex.Message & vbCrLf & vbCrLf & ex.StackTrace
            Return RedirectToAction("HttpError", "Error")
        Finally
            If Not setting Is Nothing Then setting.Dispose() : setting = Nothing
        End Try

    End Function

    <HttpPost()> _
    Public Function DeleteDisclosure(id As Integer) As ActionResult

        Dim setting As Disclosure = Nothing
        Dim x As Integer = 0

        Try
            setting = DisclosureRepository.One(Function(d) d.WebRoleID = id)
            x = setting.ID

            If TryUpdateModel(setting) Then
                DisclosureRepository.Delete(x)
            End If

            Return RedirectToAction("SelectDisclosures", setting)

        Catch ex As Exception
            Return Content("Error")
        Finally
            If Not setting Is Nothing Then setting.Dispose() : setting = Nothing
        End Try

    End Function

#End Region
...