簡體   English   中英

MVC 4如何在單擊列表項時將對象傳遞給局部視圖?

[英]MVC 4 How to pass an object to partial view when list item is clicked?

這是一個控制器

 public class ProductController : Controller
{
    //
    // GET: /Product/

    public ActionResult Index(int id = 0)
    {
        return View(DALCategory.GetCategoryList());
    }

    public PartialViewResult productPartial(int id)
    {
        if (id > 0)
        {
            return PartialView("_productPartial", DALProduct.GetProductListByCateDetail(id));
        }
        else
        {
            return PartialView("_productPartial", DALProduct.GetProductList());
        }


    }

這是索引視圖中的代碼

      @model IEnumerable<Model.Category>
        <h2>Products</h2>


        <table>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.name)
                </th>
            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.ActionLink(@item.name, "productPartial", new { id = item.id })
                    </td>
                </tr>
            }
        </table>
@Html.Partial(productPartial)

這是部分視圖的代碼。

@model IEnumerable<Model.Product>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.SKU)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.product_name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.price)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.SKU)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.product_name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.price)
        </td>
        <td>
@*            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })*@
        </td>
    </tr>
}

</table>

所以我想要做的是......當單擊一個項目時,它會使用一個新對象呈現部分。 是的,部分視圖僅在同一頁面上呈現。 我做了很多事。 雖然我認為這不是一個很難的問題,但我不確定我需要做些什么......

由於您要更新頁面的一部分,因此需要使用ajax來完成此操作。 你有兩個選擇:

  1. User @ Ajax.ActionLink( 如何在視圖中加載局部視圖

  2. 您可以編寫自己的jquery ajax請求來調用控制器方法並返回局部視圖。

它也發生在我身上。 我希望頁面是部分的並加載在同一頁面上,但它一直轉發我到其他鏈接。 確保以下幾點得到照顧:

  1. 您已經包含了jquery-1.6.2.js或此文件的任何版本。

  2. 還要包含您創建的jquery文件。 確保首先包含上述內容。

  3. 如果您已將這些文件包含在.cshtml部分的某些部分中,請確保在_Layout.cshtml或您正在使用的其他布局文件中呈現它。 例如,您已將文件包含在index.cshtml head部分中,如下所示

    @section head {}然后你必須使用@RenderSection("head", required: false)_layout.cshtml呈現此部分

    1. 您還可以做的是確保jQuery不包含兩次,並且您沒有一些javascript錯誤。 查看瀏覽器中的javascript控制台以及“網絡”選項卡,確保正確包含所有腳本。

祝好運!!!

暫無
暫無

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

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