简体   繁体   English

发送数据到局部视图

[英]Send data to partial view

Want to implement search functionality using partial view for the returned data. 想要使用部分视图来实现返回数据的搜索功能。

My html : 我的html:

<select id="searchSelect">
    <option value="All">All</option>
    <option value="Title">Title</option>
    <option value="Category">Category</option>
    <option value="ISBN">ISBN</option>
</select>

@Html.DropDownList("Categories", "Select Category")
<input type="text" id="SearchBy" placeholder="sometext" />
<a href="javascript:void(0);" class="search">Search</a>

Now, how to pass these values to partial view ?? 现在,如何将这些值传递给局部视图? - And how to load partial ?? -以及如何加载部分?

I have made this function : 我做了这个功能:

$(document).on("click", ".search", function () {
    var searchBy = $("#searchSelect option:selected").val();
    if (searchBy == "All") {
        var text = $("#SearchBy").val();
        $.ajax({
            type: "POST",
            url: "Search",
            data: JSON.stringify({ "data": text }),
            success: function (r) {
                $(".load").html(r.data);
            }
        });
    }
});

But i realize that this way i should use JSON. 但是我意识到这种方式我应该使用JSON。

You must implement Search action in your default controller to return PartialViewResult and then in the success callback of the ajax request you will receive the desired html. 您必须在默认控制器中实现Search操作以返回PartialViewResult ,然后在ajax请求的成功回调中,您将收到所需的html。

The Ajax call: Ajax调用:

[ ... ]

var text = $("#SearchBy").val();
$.ajax({
    type: "POST",
    url: "Search",
    contentType: "application/json", // Specify the content type
    data: JSON.stringify({ "data": text }), // Here you pass data to the controller's action
    success: function (response) {
        $(".load").html(response);
    }
});

[ ... ]

Search Action in HomeController : HomeController中执行搜索操作:

public ActionResult Search(string data)
{
    // Here use data, call some service or whatever
    MyModel myModel = myService.GetMyModel();

    [ ... ] 

    return PartialView(someModel);
}

Search.cshtml partial view: Search.cshtml部分视图:

@model MyModel

@{
    Layout = null;
}

<h1>@Model.Prop1</h1>
<h2>@Model.Prop2</h2>

[ ... ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM