我们可以使用Html.Partial Helper附加jQuery中的HTML(大块)吗? C#ASP.Net MVC 5 [英] Can We Append (Chunk of) HTML in jQuery using Html.Partial Helper? C# ASP.Net MVC 5

查看:167
本文介绍了我们可以使用Html.Partial Helper附加jQuery中的HTML(大块)吗? C#ASP.Net MVC 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我有一个HTML块放在我的PartialView中:

As the title suggests, I have a chunk of HTML which I put in one of my PartialView:

<div id="meaningPart">
  @Html.Partial("_Meaning", new MeaningModel() {number = 1})
</div>

其中我的_Meaning部分View看起来像这样:

where my _Meaning partial View looks like this:

<div class="chunk">
   <!--a lot of html here-->
</div>

然后,我创建一个jQuery,它对<input type="number"/>事件(上下)进行响应,如下所示:

Then, I create a jQuery which respond to a <input type="number"/> event (up and down) like the following:

<input id="numberMeaning" type="number" class = "col-md-2 form-control form-control-plus number-input" min = "0" max = "99" value = "1"/>

$(document).ready(function () {
  var iCnt = 0;

  $("#numberMeaning").on('change', function () {
    var num = parseInt($("#numberMeaning").val());
    if (num > iCnt) { //up
      iCnt++;       
      $("#meaningPart").append("<p>ok dude, this is really a new item!</p>");
    } else { //down
      iCnt--;
    }
  });
});

现在,上面的代码可以正常工作,因为我只是将"<p>ok dude, this is really a new item!</p>"放在jQuery append中,但是如果我更改此部分:

now, the above code works fine because I simply put "<p>ok dude, this is really a new item!</p>" in the jQuery append, but if I change this part:

$("#meaningPart").append("<p>ok dude, this is really a new item!</p>");

进入

$("#meaningPart").append("@Html.Partial("_Meaning", new MeaningModel() {number = 2})"); //by right, the number should follow iCnt here.

然后,尽管剃刀引擎显示语法正确,但是新的Partial HTML却无法呈现.

Then, although the razor engine shows that the syntax is correct, the new Partial HTML just doesn't render.

如何使用jQuery创建新的部分HTML?那可能吗?

How do we create a new partial HTML using jQuery? Is that possible?

(我对template属性或jQuery.clone不太熟悉-但是如果任何人都可以展示如何使用这些属性来完成html元素的添加,那么我也对此持开放态度)

(I am not too familiar with template attribute or jQuery.clone - but if it anyone can show how the adding to the html element can be done using those, I am open to that too)

推荐答案

尝试如下所示

$(document).ready(function () {
  var iCnt = 0;

  $("#numberMeaning").on('change', function () {
    var num = parseInt($("#numberMeaning").val());
    if (num > iCnt) { //up
      iCnt++;       
      // your GET /Controller/Action should return "partial HTML" based on iCnt
      $("#meaningPart").append($('<div>').load("/Controller/Action?iCnt=" + iCnt));
    } else { //down
      iCnt--;
    }
  });
});

您在控制器中的操作,例如

your Action in Controller like

public ActionResult Action(int iCnt)
{
    //get model based on 'iCnt'
    var model = GetModel(iCnt);  
    return PartialView("~/views/Folder/partialview.cshtml", model);
}

这篇关于我们可以使用Html.Partial Helper附加jQuery中的HTML(大块)吗? C#ASP.Net MVC 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆