我如何可以使通过AJAX的局部视图?视图、局部、AJAX

2023-09-10 13:52:50 作者:会撩人的粪

这应该是MVC的专家那里比较简单,但我仍然在学习的绳索。

This should be relatively simple for the MVC experts out there, but I'm still learning the ropes.

在我有一个观点是不强类型,简单地的ViewPage&LT;动态&GT; 在这种观点,我有一个文本框,这是使用jQuery的自动完成扩大 当用户键入的东西到文本框,自动完成做一个AJAX调用一个控制器,它调用存储过程,返回记录的JSON集合,有2个属性: ID (标识符的项目) 名称(名称为项) I have a View which is not strongly-typed, simply ViewPage<dynamic>. On this View, I have a single textbox, which is extended using jQuery's AutoComplete When the user types something into the textbox, the AutoComplete does an AJAX call to a Controller, which calls a stored procedure, returning a JSON collection of records, with 2 properties: ID (Identifer for the item) Name (Name for the item)

现在,随着jQuery的自动完成界面插件,当用户点击所显示的自动完成的项目之一,一个客户端事件被调用,通过JSON对象:

Now, with the jQuery AutoComplete UI Plugin, when a user clicks one of the items that is shown in the autocomplete, a client-side event is called, passing through the JSON object:

// .. snip heaps of jQuery
select: function (event, ui) {
   // ui is a JSON object:
   //    ui.item.id
   //    ui.item.name
}

现在的问题是 - 从该客户端的事件,我需要显示在同一页(texbox下文),扩展的有关该项目的信息。 (显然需要另一种AJAX调用服务器)。

Now my question is - from this client-side event, I need to display on the same page (below the texbox), extended information about this item. (obviously will require another AJAX call to the server).

我怎么能这样做?我唯一​​能想到的就是简单地使jQuery的调用另外一个控制器,它返回一个 JsonResult ,并手动解析此JSON,显示我想要的HTML。

How can I do that? The only thing I can think of is simply make the jQuery call another controller which returns a single JsonResult, and manually parse this JSON, displaying the HTML I want.

这是唯一的方法是什么?是否有一个帮手,我可以使用?究其原因我认为是不强类型,因为在页面加载时,没有显示关于模型,一个简单的文本信息。

Is that the only way? Is there a helper I can use? The reason my View is not strongly-typed is because when the page loads, there is no information displayed about the model, simply a textbox.

我真的很希望我能创建一个强类型的局部视图,并以某种方式调用这个局部视图的RenderPartial,路过我想要显示的项目的ID。这是可能的,从客户端/ AJAX?

I was really hoping I could create a partial view that is strongly-typed, and somehow call RenderPartial on this partial view, passing through the id of the item I want to display. Is this possible from client-side/AJAX?

推荐答案

您可以使用jQuery从控制器中请求HTML和JSON。所以,你的jQuery的可能是这样的:

You can use jQuery to request html as well as Json from the controller. So your jQuery could look like this:

$.get(action, null, function(data){
  $('#someDiv').html(data);
}, 'html');

和你的控制器可以返回:

and you controller could return:

return PartialView("SomePartial", Model)

和HTML会被渲染到屏幕

And the html would be rendered to the screen