C#MVC根据下拉列表选择更改图表/图表

时间:2014-08-22 09:21:31

标签: c# asp.net-mvc graph visual-studio-2013 html-select

我正在尝试创建一个简单的图形项目,用户从下拉列表中选择一个图形,然后加载生成的图形。目前我的图表已加载但会转到交换机的默认部分,正如用户未进行选择所预期的那样。当用户选择"图1"和点击提交没有真正发生的地址现在显示

http://localhost:51493/GraphDropdownModels?searchGraph=Graph+1 

但图表保持不变?

我也尝试在case语句中调用Chart():

            switch (searchGraph)
        {
            case "Graph 1":
                graphselected = "1";
                Chart()
                break;
            case "Graph 2":
                graphselected = "2";
                Chart()
                break;
            case "Graph 3":
                graphselected = "3";
                Chart()
                break;
            case "Graph 4":
                graphselected = "4";
                Chart()
                break;
        }

然而,这种接缝会循环,但图形图像永远不会被绘制。

有人能指出我的解决方案吗?

Index.cshtml

@model IEnumerable<TestSolution.Models.GraphDropdownModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("Index", "GraphDropdownModels", FormMethod.Get))
{
<p>
    Graph: @Html.DropDownList("searchGraph", "Graph 1")
    <input type="submit" value="Select" />
</p>
}
@*Render chart here*@
@{ Html.RenderAction("Chart");}
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.GraphName)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.GraphName)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.GraphID }) |
                @Html.ActionLink("Details", "Details", new { id = item.GraphID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.GraphID })
            </td>
        </tr>
    }
</table>

GraphDropdownModelControler.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;
using TestSolution.Models;

namespace TestSolution.Controllers
{
public class GraphDropdownModelsController : Controller
{
    private GraphingDBContext db = new GraphingDBContext();
    private string graphselected = "Graph 1";


    // GET: GraphDropdownModels
    public ActionResult Index(string searchGraph)
    {
        string item1 = "Graph 1";
        string item2 = "Graph 2";
        string item3 = "Graph 3";
        string item4 = "Graph 4";
        var GraphLst = new List<string> { item1, item2, item3, item4 };
        ViewBag.searchGraph = new SelectList(GraphLst);

        switch (searchGraph)
        {
            case "Graph 1":
                graphselected = "1";
                break;
            case "Graph 2":
                graphselected = "2";
                break;
            case "Graph 3":
                graphselected = "3";
                break;
            case "Graph 4":
                graphselected = "4";
                break;
        }

        return View(db.GraphNames.ToList());
    }
    public ActionResult Chart()
    {
        var chart = buildChart();
        StringBuilder result = new StringBuilder();
        result.Append(getChartImage(chart));
        result.Append(chart.GetHtmlImageMap("ImageMap"));
        return Content(result.ToString());
    }

    private Chart buildChart()
    {
        // Build Chart
        var chart = new Chart();
        chart.Width = 800;
        chart.Height = 600;

        // Create chart here
        chart.Titles.Add(CreateTitle());
        chart.Legends.Add(CreateLegend());
        chart.ChartAreas.Add(CreateChartArea());
        chart.Series.Add(CreateSeries());

        return chart;
    }

    private string getChartImage(Chart chart)
    {
        using (var stream = new MemoryStream())
        {
            string img = "<img src='data:image/png;base64,{0}' alt='' usemap='#ImageMap'>";
            chart.SaveImage(stream, ChartImageFormat.Png);
            string encoded = Convert.ToBase64String(stream.ToArray());
            return String.Format(img, encoded);
        }
    }

    private Title CreateTitle()
    {
        // Create instance of title            
        Title title = new Title();

        // Set title using variable
        String chartTitle = "Custom Chart Result";
        title.Text = chartTitle;

        // Set font style
        title.Font = new Font("Trebuchet MS", 14F, FontStyle.Bold);
        title.ForeColor = Color.FromArgb(26, 59, 105);

        return title;
    }

    private Legend CreateLegend()
    {
        //Initializes a new instance of the Legend class.
        Legend legend = new Legend();

        // show/hide legend
        legend.Enabled = true;

        //set legend content font style , colour 
        legend.Font = new Font("Trebuchet MS", 14F, FontStyle.Bold);
        legend.ForeColor = Color.FromArgb(26, 59, 105);

        // Set legend title            
        legend.Title = "Legend";

        return legend;
    }


    private ChartArea CreateChartArea()
    {
        // Initializes a new instance of the ChartArea class called chartArea.
        ChartArea chartArea = new ChartArea();

        // Sets name of the chart object
        chartArea.Name = "Result Chart";

        // sets the background color of the ChartArea object.
        chartArea.BackColor = Color.LightGray;

        // Show Axis labels on/off
        chartArea.AxisX.IsLabelAutoFit = true;
        chartArea.AxisY.IsLabelAutoFit = true;

        // Set axis label font style
        chartArea.AxisX.LabelStyle.Font = new Font("Verdana,Arial,Helvetica,sans-serif", 8F, FontStyle.Regular);
        chartArea.AxisY.LabelStyle.Font = new Font("Verdana,Arial,Helvetica,sans-serif", 8F, FontStyle.Regular);

        // Set colour of x/y edge lines 
        chartArea.AxisY.LineColor = Color.FromArgb(64, 64, 64, 64);
        chartArea.AxisX.LineColor = Color.FromArgb(64, 64, 64, 64);

        // Set x/y grid lines colour & set interval between lines 
        chartArea.AxisY.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
        chartArea.AxisX.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
        chartArea.AxisY.Interval = 1;
        chartArea.AxisX.Interval = 1;
        return chartArea;
    }

    public Series CreateSeries()
    {
        Series seriesDetail = new Series();
        // adjust legend data name
        seriesDetail.Name = "Result!";

        seriesDetail.IsValueShownAsLabel = false;
        // Sets Colour of Bar/Segments/Data ect 
        seriesDetail.Color = Color.FromArgb(198, 99, 99);

        // Set the Chart Type
        seriesDetail.ChartType = SeriesChartType.Column;
        // NO IDEA ATM
        seriesDetail.BorderWidth = 1;


        // Adjust the Chart Series values used for X + Y
        if (!String.IsNullOrEmpty(graphselected))
        {
            switch(graphselected)
            {
                case "1":
                    seriesDetail.Points.AddXY("Cats", 1);
                    seriesDetail.Points.AddXY("Dogs", 3);
                    seriesDetail.Points.AddXY("Bats", 5);
                    seriesDetail.Points.AddXY("Mouse", 2);
                    break;
                case "2":
                    seriesDetail.Points.AddXY("Cats", 10);
                    seriesDetail.Points.AddXY("Dogs", 30);
                    seriesDetail.Points.AddXY("Bats", 50);
                    seriesDetail.Points.AddXY("Mouse", 20);
                    break;
                case "3":
                    seriesDetail.Points.AddXY("Cats", 100);
                    seriesDetail.Points.AddXY("Dogs", 300);
                    seriesDetail.Points.AddXY("Bats", 500);
                    seriesDetail.Points.AddXY("Mouse", 200);
                    break;
                case "4":
                    seriesDetail.Points.AddXY("Cats", 1000);
                    seriesDetail.Points.AddXY("Dogs", 3000);
                    seriesDetail.Points.AddXY("Bats", 5000);
                    seriesDetail.Points.AddXY("Mouse", 2000);
                    break;
                default:
                    seriesDetail.Points.AddXY("H", 1);
                    seriesDetail.Points.AddXY("E", 5);
                    seriesDetail.Points.AddXY("L", 5);
                    seriesDetail.Points.AddXY("P", 1);
                    break;

            }
        }


            //sets the name of the ChartArea object used to plot the data series
            seriesDetail.ChartArea = "Result Chart";
            return seriesDetail;

    }



    // GET: GraphDropdownModels/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        GraphDropdownModel graphDropdownModel = db.GraphNames.Find(id);
        if (graphDropdownModel == null)
        {
            return HttpNotFound();
        }
        return View(graphDropdownModel);
    }

    // GET: GraphDropdownModels/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: GraphDropdownModels/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "GraphID,GraphName")] GraphDropdownModel graphDropdownModel)
    {
        if (ModelState.IsValid)
        {
            db.GraphNames.Add(graphDropdownModel);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(graphDropdownModel);
    }

    // GET: GraphDropdownModels/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        GraphDropdownModel graphDropdownModel = db.GraphNames.Find(id);
        if (graphDropdownModel == null)
        {
            return HttpNotFound();
        }
        return View(graphDropdownModel);
    }

    // POST: GraphDropdownModels/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "GraphID,GraphName")] GraphDropdownModel graphDropdownModel)
    {
        if (ModelState.IsValid)
        {
            db.Entry(graphDropdownModel).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(graphDropdownModel);
    }

    // GET: GraphDropdownModels/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        GraphDropdownModel graphDropdownModel = db.GraphNames.Find(id);
        if (graphDropdownModel == null)
        {
            return HttpNotFound();
        }
        return View(graphDropdownModel);
    }

    // POST: GraphDropdownModels/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        GraphDropdownModel graphDropdownModel = db.GraphNames.Find(id);
        db.GraphNames.Remove(graphDropdownModel);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

}

1 个答案:

答案 0 :(得分:0)

好的找到了我的问题的解决方案。

问题是变量,公共字符串graphselected;在变量上添加监视后,我可以看到在代码运行时值被删除,因此值始终为null。所需要的只是添加“#34; static&#34;确保变量不会被丢弃。

修复:公共静态字符串graphselected;