如何在MVC的部分视图中回发数据?

问题描述:

我有一个主视图和两个局部视图

I have a main view and two partial views

  1. 索引-主视图
  2. _详细信息-部分视图
  3. _Address-详细信息局部视图内的局部视图

索引-主视图

    @model IndexViewModel
    @{
        Layout = "~/Views/Shared/_CodeLayout.cshtml";

    }

@Html.Partial("_Details", Model)

2. _Details-局部视图

     @model IndexViewModel
<div id="Detailsdiv">  



    @using (Html.BeginForm("_Details", "FS", FormMethod.Post, new
        {
            id =
              "frmFS",
            @class = "form-horizontal"
        }))
    { 

    <div class="row">
        <div class="col-lg-1 nopadding">
            <div class="col-lg-1 nopadding">
                @Html.LabelFor(m => m.User.Name):
            </div>
            <div class="col-lg-2">
                @Html.TextBoxFor(m => m.User.Name, new { @id = "txtName", @style = "width:140px;height:24px", @maxlength = "25" })
            </div>
        </div>
    </div>
  @Html.Action("_Address", "Shared", new { userId = Model.User.UserId })
        }
        <button type="button" value="Save" ID="btnSave"> Save </button>
        }
    </div>

3. _地址-部分视图

@model AddressViewModel 

<div id="divAddress">

    @using (Html.BeginForm("_Address", "Shared", FormMethod.Post, new { id = "frmAddress", @class = "form-horizontal" }))
    {
<div class="row">
<div class="col-lg-1 nopadding">
                                    @Html.LabelFor(m => m.Address.AddressDesc):
                                </div>
                                <div class="col-lg-2">
                                    @Html.TextBoxFor(m => m.Address.AddressDesc, new { @id = "txtAName", @style = "width:140px;height:24px", @maxlength = "25" })
                                </div>
</div>
---
-
-
And some more 
  <button type="button" value="Save" ID="btnCreate"> Create </button>
</div>

}



   $('#btnCreate').click(function () {

                $("#ajax_loader").show();
                 var inputdata = $("#frmAddress").serialize();
                $.ajax({
                    url: '@Url.Action("CreateAddress", "Shared")',
                    type: 'POST',
                    cache: false,
                    data: inputdata
                }).done(function (result) {
                    $("#divAddress").html(result);
                    $("#ajax_loader").hide();
                });

        });

SharedConroller

获取地址操作

public ActionResult _ Address (short userId )
        {


}

public ActionResult CreateAdderess(AddressViewModel addressViewModel)
        {
Create address…………..
But AddressViewModel is coming null 
}
    }


public class AddressViewModel
{
    [Key]
    public decimal AddressId { get; set; }


    [DisplayName("Address Type")]

    public string Addr_Typ { get; set; }
    [DisplayName("Address Description")]
    [MaxLength(256)]
    public string Addr_Desc { get; set; }
    [DisplayName("City")]
    [MaxLength(30)]
    public string City_Nm { get; set; }

    [DisplayName("State")]
    [MaxLength(2)]
    public string State_Cd { get; set; }

    [DisplayName("Zip")]
    [RegularExpression(@"^\d{5}(?:[\-]?\d{4})?$", ErrorMessage = "Invalid Zip")]
    [MaxLength(10)]
    public string Zip { get; set; }
}

从_Details回发正在工作.从地址-部分"视图发回邮件不起作用.

Post back from the _Details is working. Post back from the Address- partial view is not working.

预先感谢

页面上可以有多种形式.例如,如果您有一个包含要删除任何行的行的表,则可以在该行的表单元格中创建一个表单.这样,删除操作只需一个ID即可执行POST操作.

You can have multiple forms on a page. For example, if you have a table with rows where you want to delete any row, you an create a form in a table cell on that row. In this way, the delete takes only one id to the POST action for delete.

我建议您将局部视图分成各自的形式,每个独立地起作用.唯一的问题是,如果一种形式的更新要求重新显示另一种形式.您的外部视图比试图进行通信的部分视图可以更好地处理该问题.简单地从一个操作中返回JSON对象中两个视图的结果,并将HTML分配给每个具有部分视图的DIV

I suggest you split your partial views up into their own forms, each one acting independently. The only issue with this is if an update in one form requires the other to be redisplayed. Your outer view can handle that better than partial views trying to communicate. It is a simple matter to return the results of two views in a JSON object from an action and assigned the HTML to each of the corresponding DIV that has the partial view

首先有两个填充部分的选择.如果您的主视图中有类似的内容,那么在第一次加载时,您的详细信息HTML就会由RAZOR引擎呈现到div中.这来自HTTP GET操作(假设您在GET和POST上有单独的操作)

You have two choices of initially populating your partial. If you have something like this in your main view, on first load, your details HTML is rendered by the RAZOR engine into the div. This comes from the HTTP GET action (assuming you have separate ones for GET and POST)

<div id="divYourPartial">
    @Html.Partial("_Details", Model)
</div>

当用户保存(POSTS)他们的更改时,我在第一个答案中建议的代码将重新填充此DIV.您无事可做.

The code I suggested in the first answer will then repopulate this DIV when a user saves (POSTS) their changes. There is nothing more for you to do.

您也可以使用JavaScript首次加载div,就像我的第一个答案一样

You can also populate the div on first load using JavaScript, as in my first answer

<div id="divYourPartial">
</div>

您将需要一个脚本部分来最初执行加载-除非您等待用户单击某些元素并按ID加载数据.如果要捕获动态加载的后代中的事件,请将事件处理程序放在固定的外部元素上,否则您将无法捕获它们.

You will need a scripts section that performs the load initially - unless you wait for a user to click some element and load the data by ID. If you want to capture events from descendants that are dynamically loaded, put an event handler on a fixed, outer element otherwise you won't catch them.

        @section Scripts
        {
            <script type="text/javascript">

function LoadData(){
$.ajax({
    url: '/YourController/YourAction/' + YourId,
    type: "get",
    success: function (result) {
    $("#divYourPartial").html(result);
    }
});
}


        $(function () {
// first time page load
LoadData()

    $("#divOuter").on("dblclick", function (event) {
    // when user double clicks an item, show it for editing
    // on an outer div awaiting an event to percolate up from a descendant, the target is not $(this)
    var target = $(event.target);

    // Your ajax here to load the div
        });
    });
    </script>