ASP.NET MVC 3 Charting and HTTPPOST - asp.net

Working in Asp.Net MVC 3.
Controller Code:
[HttpPost]
public ActionResult MyChart(string sDate)
{
/*Call Entity Database*/
Contact_Center_DashboardEntities3 db = new Contact_Center_DashboardEntities3();
var results01 = db.sp_Report_Hybrid_Metrics("9 September", sDate, "Auto", "R2/R8", "Claims", "Claims", "R02_R08.AUTO.CLM.FMN.Q").ToList();
var chart = new Chart();
chart.Width = 1000;
chart.Height = 200;
var area = new ChartArea();
// configure your chart area (dimensions, etc) here.
chart.ChartAreas.Add(area);
area.AxisX.MajorGrid.Enabled = false;
area.AxisY.MajorGrid.Enabled = false;
area.AxisY2.MajorGrid.Enabled = false;
area.AxisY2.LabelStyle.Format = "0%";
// create and customize your data series.
var series = new Series();
foreach (var item in results01)
{
series.Points.AddXY(item.Date, item.Volume);
}
series.Font = new Font("Segoe UI", 8.0f, FontStyle.Bold);
series.ChartType = SeriesChartType.Column;
series.YAxisType = AxisType.Primary;
// create and customize your data series.
var seriesSecondary = new Series();
foreach (var item in results01)
{
seriesSecondary.Points.AddXY(item.Date, item.XferPer);
}
seriesSecondary.Font = new Font("Segoe UI", 8.0f, FontStyle.Bold);
seriesSecondary.ChartType = SeriesChartType.Line;
seriesSecondary.YAxisType = AxisType.Secondary;
seriesSecondary.LabelFormat = "0%";
seriesSecondary.IsValueShownAsLabel = true;
chart.Series.Add(series);
chart.Series.Add(seriesSecondary);
var returnStream = new MemoryStream();
chart.ImageType = ChartImageType.Png;
chart.SaveImage(returnStream);
returnStream.Position = 0;
return new FileStreamResult(returnStream, "image/png");
}
Tables View Code:
#using (Html.BeginForm("MyChart", "Home", FormMethod.Post))
{
<fieldset>
<div class="editor-field">
<input type="submit" value="09/06/2014" name = "sDate"/>
</div>
</fieldset>
}
When the user clicks the Submit button, the value passes to the "MyChart" ActionResult correctly, but then takes me to the MyChart view. What I need it to do is pass the value through, stay on the Tables View, and refresh the chart.

You could try something like this:
#using (Ajax.BeginForm("MyChart", "Home", new AjaxOptions{HttpMethod= "Post", UpdateTargetId = "chartContainer", InsertionMode = InsertionMode.Replace}))
{
<fieldset>
<div class="editor-field">
<input type="submit" value="09/06/2014" name = "sDate"/>
</div>
</fieldset>
}
<div id="chartContainer">
</div>
The request is done by ajax and inserts the response of the request into the element addressed by updatetargetid. If the submit button should be deleted after clicking it once, place the form inside the div. Otherwise the chart would be refreshed overtime you press the submit-button.

Related

How can i get Kendo Grid DataItem

How can i get the selected row KendoGrid Data Item?
I research a lot online and I came across this post http://dojo.telerik.com/egUpI which does exactly what i am looking for i would like implement the same.
I have the following code to populate grid in asp.net view. I need your help when row selected populate a elements.
Here is my Grid View:
<h1> Contacts</h1>
#{
var gridColumnSettings = new List<GridColumnSettings>
{
new GridColumnSettings
{
Member = nameof(Contact.Name),
MemberType = typeof(string)
},
new GridColumnSettings
{
Member = nameof(Contact.PhoneNumber),
MemberType = typeof(string)
}
};
var gridViewModel = new GridViewModel
{
Name = "ContactGrid", // Grid Name
Columns = gridColumnSettings,
AutoBind = true,
DataSourceSettings = new GridDataSourceSettings
{
ReadDataSource = new DataSourceSetting()
{
ActionName = "Contact",
ControllerName = "Contact",
HttpVerb = HttpVerbs.Get,
}
},
SelectionSettings = new GridSelectionSettings
{
IsSelectable = true, // To make grid selectable
GridSelectionMode = 0,
GridSelectionType = 0
},
}
};
}
Here is my Form on the same Page to display the selected grid row information
<form>
<h3>Name</h3>
<div class="col-sm-3">
<input type="text" readonly class="form-control " id="Name">
</div>
<h3>Phone</h3>
<div class="col-sm-3">
<input type="text" readonly class="form-control" id="Phone">
</div>
</form>
I tried this Jquery, but not working
<script>
function fillForm() {
$("#ContactGrid").kendoGrid({
change: function (e) {
var dataItem = this.dataItem(this.select());
fillForm(dataItem);
}
});
}
// Fill Form based on the selected row
var fillForm = function(dataItem) {
var columns = $("#ContactGrid").data("kendoGrid").options.columns;
var form = $("form");
for (var i = 0; i < columns.length; i++) {
var field = columns[i].field;
form.find("#" + field).val(dataItem[field]);
}
}
</script>

how to pagination razor page?

i have a table for saving some ids for send request to web service and save my data to view model and show data in view page with IEnumerable viewmodel.Now i want to have a pagination at the end of my page because i have more than 100 product in my archive page.Now how can i have Pagination for this page??
//CONTROLLER
public ActionResult Archive()
{
var selectspecial = db.ProviderSelections.Where(a =>
a.SpecialSuggestion == true && a.IsActive ==
true).OrderByDescending(a => a.CreateDate).Select(a =>
a.ID).ToList();
var lastitem = selectspecial.Last();
List<string> lst = new List<string>();
for (int i = 0; i < selectspecial.Count; i++)
{
var selectid = selectspecial[i];
lst.Add(selectid.ToString());
}
StringBuilder itemlist = new StringBuilder();
foreach (var item in lst)
{
itemlist.Append(item).Append(",");
}
string id = itemlist.ToString() + lastitem;
WebClient webclient = new WebClient();
webclient.Headers[HttpRequestHeader.ContentType] =
"application/json;charset=utf-8";
string url = "MYWEBSERVICEURL?pids=" + id;
webclient.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("USERNAME:PASSWORD"));
webclient.Headers.Add("Request-type", "REQUESTTYPE");
string result = webclient.DownloadString(url);
JObject jObject = JObject.Parse(result);
JToken jUser = jObject["X"];
List<BriefDetailsViewModel> briefdetails = new
List<BriefDetailsViewModel>();
foreach (var item in jUser)
{
BriefDetailsViewModel brief = new BriefDetailsViewModel();
brief.address = (string)item["address"];
//OTHER LINES ARE LIKE ABOVE LINE
briefdetails.Add(brief);
}
return View(briefdetails);
}
//Archive.cshtml
#model IEnumerable<ROOT.BriefDetailsViewModel>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
#foreach (var item in Model)
{
<div class="col-lg-9 col-md-9 col-sm-8 col-xs-8">
<div class="text TextBox">
#item.description
</div>
</div>
//More Data like this....
}
//PAGINATION BOX
</div>
The best practice by adding pagination feature to your web service to be like this :
string url = "MYWEBSERVICEURL?pids=" + id + "&pageId="+pageId;
Also use page size variable, then you can page your data using LINQ :
example :
int numberOfObjectsPerPage = 10;
var queryResultPage = dataContext.Employees.OrderBy(a=>a.ID)
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(numberOfObjectsPerPage).ToList();
If you cannot update your web service, or you are using external web service you can read the data then page it before return your view :
briefdetails = briefdetails
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(numberOfObjectsPerPage);
return View(briefdetails);
Also in your html you can render something for paging below your table :
//You called it PAGINATION BOX
for(int i=1,i<pageNumber;i++)
{
<a href="#Url.Action("YOUR_ACTION",new {pageId = i})">#i<a/>
}

How do I pass an id of a clicked button to controller using AjaxBeginForm?

I'm using #Ajax.BeginForm() with KendoUI ListView in my asp.net mvc3 application. The KendoUI ListView displays a list of Items with a button for each item.
My requirement is that onclick of submit button, I need to send the id of a clicked button to the controller and return the full information of the Item.
My approach was to use onclick function for all buttons to trigger AjaxBeginForm submit input but the AjaxBeginForm submit input doesn't seems to pass the right value into the controller,
How can I achieve this?
<pre>
//My Ajax form
var ajaxOpts = new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "gallery",
InsertionMode = InsertionMode.Replace,
OnBegin = "OnBeginT1",
};
#using (Ajax.BeginForm("BlogInformation", ajaxOpts))
{
<input id="input" type="submit" style="display: none"/>
}
<script id="listview-template" type="x-kendo-template">
<button class="k-button1" onclick="returnsubmitted()" id="#:id#" name="but">Read More</button>
//Displaying a list
</div>
#(Html.Kendo().ListView<Blog>()
.Name("listView")
.TagName("div")
.ClientTemplateId("listview-template")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("Blog_Read", "Blog"));
})
)
<script>
function returnsubmitted() {
//$("input").val($("#:id#").val());//This does not pass the right value to input
// $("#input").val($('.k-button1').attr('class').id);
$("#input").click();
}
</script>
//Here is my controller
[HttpPost]
public ActionResult BlogInformation(string blogid)
{
XElement element = XElement.Load(Server.MapPath("~/App_Data/Blogs.xml"));
IEnumerable<Blog> data = null;
if (!string.IsNullOrEmpty(blogid))
{
var xElement = FindByID(blogid, element.Element("Blog")).Element("Blog");
if (xElement != null)
{
data = FindByID(blogid, element.Element("Blog"))
.Element("items")
.Elements("Blog")
.Select(e => ToBlog(e));
}
else
{
data = element.Elements("Blog").Select(e => ToBlog(e));
}
}
return View(data);
}

ASP.NET MVC4 + Get drop down value after HttpPost submit

So I want to get a value of the dropdown (== id of the account) to insert a new transaction
Here below you can find my View:
<div id="content">
<h2>Overschrijving</h2>
<p id="topmsg">velden met een * zijn verplicht</p><p> </p>
<dl class="clearfix form">
#using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
#Html.ValidationSummary(true, "Gelieve alles correct in te vullen.")
<dt>#Html.Label("Rekening: *")</dt>
<dd>#Html.DropDownList("ddlAccounts")</dd>
<dt>#Html.Label("Begunstigde: *")</dt>
<dd>#Html.TextBox("ToAccountNumber")</dd>
<dt>#Html.Label("Bedrag: *")</dt>
<dd>#Html.TextBox("Amount", null, new { #class = "inpshort" })</dd>
<dt>#Html.Label("Mededeling: ")</dt>
<dd>#Html.TextBox("Message", null, new { #class = "inplong" })</dd>
<dd class="buttons">
<input type="submit" value="Bevestigen" />
<input type="submit" value="Annuleren" />
</dd>
}
</dl>
</div>
this is the Controller code:
public ActionResult Transfer(int? id) {
Holder h = Holder.GetHolderByHolderId(Convert.ToInt32(User.Identity.Name));
List<Account> holderAccounts = Account.GetAccountsByHolderId(h.Id);
List<SelectListItem> ddlHolderAccounts = new List<SelectListItem>();
ddlHolderAccounts.Add(new SelectListItem { Text = "selecteer...", Value = "-1", Selected = true });
foreach (Account acc in holderAccounts) {
if (acc.Id == id) {
ddlHolderAccounts.Add(new SelectListItem { Text = acc.Name, Value = acc.Id.ToString(), Selected = true });
} else {
ddlHolderAccounts.Add(new SelectListItem { Text = acc.Name, Value = acc.Id.ToString() });
}
}
ViewData["ddlAccounts"] = ddlHolderAccounts;
return View();
}
[HttpPost]
public ActionResult Transfer(Transaction tra) {
if (ModelState.IsValid) {
Transaction.InsertTransaction(tra.Amount, tra.Message, tra.FromAccountId, tra.ToAccountNumber);
}
return View(tra);
}
Now I searched a lot with Google, it's probably better to use the DropDownListFor to fill your drop down list? But could anyone show me an example?
By looking at your code, I can see that you're not passing a list of SelectListItems to the DropDownList helper. You can do this one of two ways.
1- Bind it to a property on your model:
#Html.DropDownListFor(x=>Model.Property, new List<SelectListItem> { new SelectListItem { Text = "Item1", Value = "Value1" })
Or
2- You can do it without binding to a model property like:
#Html.DropDownList("propertyName", new List<SelectListItem> { new SelectListItem { Text = "Item1", Value = "Value1" } })
If you're using the second approach then your controller action must accept "propertyName" as a parameter when submitting.
And don't forget to provide a list of SelectListItems to select from (which you're not doing in your code).
Hope this helps.
should be
#Html.DropDownListFor(x=>Model.Property, new List { new SelectListItem { Text = "Item1", Value = "Value1" }})

C# MVC3 DropDownList - No ID found in the form post

I just made a form containing a DropDownList, it perfectly shows the option names, but doesn't post the ID of the selected option into the controller.
Here is the code for the controller:
[HttpGet]
public ActionResult Insert(int id)
{
TemplateRepository repo = new TemplateRepository();
List<Template> templateList = repo.ListAll().ToList<Template>();
ViewData["Template"] = new SelectList(templateList, "Id", "Omschrijving");
return View();
}
[HttpPost]
public ActionResult InsertOrEditSubmit(Klant klant)
{
KlantRepository repo = new KlantRepository();
klant.Naam = Request["Naam"];
klant.Adres = Request["Adres"];
klant.Postcode = Request["Postcode"];
klant.Woonplaats = Request["Woonplaats"];
klant.Email = Request["Email"];
klant.Telefoon = Request["Telefoon"];
repo.SaveOrUpdate(klant);
return RedirectToAction("Index");
}
And here is the code in the view:
#using (Html.BeginForm("InsertOrEditSubmit", "Klant", FormMethod.Post))
{
#Html.DevExpress().Label(
settings =>
{
settings.ControlStyle.CssClass = "label";
settings.Text = "Template";
settings.AssociatedControlName = "Template";
}
).GetHtml() <br />
#Html.DropDownList("Template", ViewData["Template"] as SelectList);
#Html.DevExpress().Button(
settings =>
{
settings.ControlStyle.CssClass = "button";
settings.Name = "Insert";
settings.Text = "Toevoegen";
settings.UseSubmitBehavior = true;
}
).GetHtml()
#Html.DevExpress().Button(
settings =>
{
settings.ControlStyle.CssClass = "button";
settings.Name = "Cancel";
settings.Text = "Terug";
settings.ClientSideEvents.Click = "function(s, e){ document.location='" + DevExpressHelper.GetUrl(new { Controller = "Gebruiker", Action = "Index" }) + "'; }";
}
).GetHtml()
}
Hope someone can explain why it doesn't post the ID..
Try: Request["Template"];
Try a simple test:
(Controller)
ViewData["Test"] = new SelectList(new[] {new {Id = 1, Text = "Test 1"}, new {Id = 2, Text = "Test 2"}, new {Id = 3, Text = "Test 3"}}, "Id", "Text");
(View)
#Html.DropDownList("Test", ViewData["Test"] as SelectList)
Now the Request["Test"] should return the Id of the selected value.
But if your View is strongly-typed, in your case to the object "Klant", you don't need to fill the values with the Request, the object will be auto-populated and if your object have a property Template it'll be populated too.
I have found that sometimes having a name along with the id for an input solves this issue.
What does your rendered html for the Template control look like?

Resources