[英]How to execute a script on partial view rendering?
我對CalculateModel
有一個強類型的視圖,在該視圖中,用戶可以向控制器添加一些信息並發布ajax
帖子,控制器在此數據中執行一些數學ResultCalculateModel
然后將強類型的PartialView返回到ResultCalculateModel
。
在Result局部視圖中,我有一個d3 chart
,該d3 chart
是使用ResultCalculateModel
具有的一些參數動態生成的。 這是一些代碼:
@model DTO.CalculateModel
//the html helpers here to user input some data
<div id='divOutPutData'> </div>
<script>
function getResult() {
$.post("/GetResult", $('#form01').serialize())
.success(function (result) {
$('#divInputData').attr('style', 'display:none');
$('#divOutPutData').append(result);
};
function drawChart(s,p,c){
//code
};
</script>
那個行動:
public ActionResult GetResult(CalculateModel model)
{
ResultCalculateModel result = _calculateResult.Calculate(model);
return PartialView("Result", result);
}
結果局部視圖:
@model DTO.ResultCalculateModel //the parameters of the drawChart function are in this model.
//some Razor Helpers which is working
<div id="chartResult"> </div> //i need to display the chart here
我想知道如何在局部視圖渲染中執行drawChart
函數?
這將有助於我認為
//example function which posts data gets result.. puts html on dom, then calls DrawChart function
function PostStuff() {
$.post("/GetResult", $('#form01').serialize()).success(function (result) {
$('#divInputData').attr('style', 'display:none');
$('#divOutPutData').append(result);
//call function to interact with the data you just injected into the dom
//get values from the partial view I made these up... you need to adjust for your situation.
var s = $("#sId");
var p = $("#pId");
var c = $("#cId");
DrawChart(s,p,c);
};
}
//example function
function DrawChart(s,p,c){
//code
};
也許在部分視圖中,.cshtml本身會在某個位置的標簽中返回您需要的參數,例如:
<div id="drawChartValues" parameter1="value1" parameter2="value2" style="display: none;">
</div>
然后在你的JavaScript中
function PostStuff() {
$.post("/GetResult", $('#form01').serialize()).success(function (result) {
$('#divInputData').attr('style', 'display:none');
$('#divOutPutData').append(result);
var p1 = $('#drawChartValues').attr('parameter1');
var p2 = $('#drawChartValues').attr('parameter2');
DrawChart(p1,p2);
};
}
您應該保留div元素(用於d3容器),並從action方法中獲取,而不是返回局部視圖,而是返回以JSON格式繪制圖形所需的數據。 在ajax調用的成功事件中,讀取數據並將其傳遞給呈現d3 grahic的js方法
public ActionResult GetResult(CalculateModel model)
{
ResultCalculateModel result = _calculateResult.Calculate(model);
return Json(result,JsonRequestBehaviour.AllowGet);
}
在您的主視圖中,保持容器div
<div id="chartResult"> </div>
在你的js里
<script>
function getResult() {
$.post("/GetResult", $('#form01').serialize())
.success(function (result) {
var s=result.SValue ;
var p = result.PValu;
var c =result.CValue;
drawChart(s,p,c);
};
}
function drawChart(s,p,c){
//code to render the grpah
};
</script>
假設SValue
和PValue
和CValue
是CValue
的3個屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.