We are using a Kendo UI date picker (Javascript version), in which I want to populate with an HttpContext.Session variable that has a date passed from our KendoUI datepicker and passed to our controller, Session is set in the controller.
The KendoUI DatePicker is used on multiple pages in multiple templates.
My goal is to have the date selected and set in Session be passed back to the KendoUI DatePicker if the variable is set. And if the date selected is not set, I want the Date Picker's value to be set to today or new Date().
My Javascript:
<script>
$(document).ready(function () {
var SelectedDate = new Date();
//Is this even correct?
if('#HttpContext.Current.Session["CalendarSelectedDate"]' != '#DateTime.Now'){
SelectedDate == '#HttpContext.Current.Session["CalendarSelectedDate"]';
console.log("In if");
}else{
SelectedDate == new Date();
console.log("In else");
}
console.log('Selected date: ' + SelectedDate);
// WANT TO SET VALUE FROM SESSION DATE HERE!!!
$("#datepicker").kendoDatePicker({
value: SelectedDate,
min: new Date(),
format: "MM/dd/yyyy",
change: function () {
var value = this.value();
console.log(value); //value is the selected date in the datepicker
initialGetEventTypes();
}
});
initialGetEventTypes();
});
</script>
//The AJAX call to the controller
<script type="text/javascript">
function initialGetEventTypes() {
#{
var dateFromHub = DateTime.Now;
var obj = HttpContext.Current.Session["CalendarSelectedDate"];
if(obj != null)
{
dateFromHub = Convert.ToDateTime(obj);
}
}
console.log('Session Selected Date: #dateFromHub.ToShortDateString()');
$('#categoryLoading').show();
var startDateTime = $("#datepicker").val();
var endDateTime = startDateTime;
var url = '#Url.Action("GetTotalEventTypeIdsByDate", "MuseumUniversalCalendar")';
$.ajax({
url: url,
type: "GET",
cache: false,
dataType: "json",
data: { startDateTime: startDateTime, endDateTime: endDateTime },
success: function (data) {
$('#categoryLoading').hide();
$('.product-item').find('.categoryAvaiableCapacity').html("Not Available");
var list = JSON.stringify(data);
$("#eventTypeName").find('option').remove().end();
$.each(data.result, function (i, eventTypes) {
$('.product-item').each(function () {
if ($(this).attr('data-galaxyeventnamefromnop') == eventTypes.EventName) {
$(this).find('.categoryAvaiableCapacity').html(eventTypes.Available + ' Available');
}
});
});
if (data.result.length === 0) {
$("#noEvents").text('#T("museum.noeventavailablemessage")');
}else{
// console.log("we are here")
$("#noEvents").text("");
}
},
error: function(xhr, error, data) {
console.log(xhr, error, data);
$('#categoryLoading').hide();
$("#eventTypeName").find('option').remove().end();
alert("An error occurred getting the Event Types");
}
});
}
</script>
My Controller method:
public class MuseumUniversalCalendarController : Controller
{
//[NonAction]
public JsonResult GetTotalEventTypeIdsByDate(MuseumUniversalCalendarModel model, DateTime startDateTime, DateTime endDateTime)
{
//Set selected Date for session
HttpContext.Session["CalendarSelectedDate"] = startDateTime;
var result = eventListOfEvents(model, startDateTime, endDateTime);
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
public List<cEvent> eventListOfEvents(MuseumUniversalCalendarModel model, DateTime startDateTime, DateTime endDateTime)
{
var eventTypeIdList = ExternalDataAccess.HubServiceCalls.GetAvailableEventsByEventDate(startDateTime, endDateTime);
foreach(var eventTypeItem in eventTypeIdList)
{
model.AvailableGalaxyEventTypes.Add(new SelectListItem
{
Text = eventTypeItem.EventName,
Value = eventTypeItem.EventTypeId.ToString()
});
}
var fullOutEventlist = eventTypeIdList;
var totalsList = eventTypeIdList.GroupBy(e => e.EventName.ToString()).Select(grp => grp.First()).ToList();
totalsList.ForEach(x => x.Available = eventTypeIdList.Where(y => y.EventName == x.EventName).Select(z => z.Available).Sum());
return totalsList;
}
I would wrap the datapicker in a partial view that can read the session value out into the view's JS with razor. You could even isolate it to its own controller.
Views/Shared/_DatePickPartial.cshtml
<div id='datepicker'></div>
<script>
$("#datepicker").kendoDatePicker({
value: '#HttpContext.Session["CalendarSelectedDate" ] ?? new Date()',
min: new Date(),
format: "MM/dd/yyyy",
change: function () {
//send ajax to partial action DatePickPartialUpdate which will add value to session
}
});
</script>
SomeController _DatePickPartial
public ActionResult _DatePickPartialUpdate(DateTime2 value)
{
Session["CalendarSelectedDate"] = value;
}
Related
I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have an appointments application with multiple users who can multiple appointments. I display this on FullCalendar.
However, I'm having a problem. I want the User logged in to see their events and not others. This works when I close the application completely but if I log out and want to login as another user, I see the other users appointments.
I tried using re fetch events with FullCalendar then I looked at the Configuration.ProxyCreationEnabled = false; within my DAL class.
Here's my controller method:
public JsonResult GetEvents()
{
string username = Membership.GetUser().UserName;
var getAdmin = (from a in db.Admins
where username == a.AdminUsername
select a.AdministrationId).SingleOrDefault();
var events = (from a in db.Appointments
where getAdmin == a.AdministrationId
select a).ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And FullCalendar:
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Appointments/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
details: v.DetailsOfAppointment,
date: moment(v.DateOfAppointment),
room: v.RoomType,
confirmed: v.Confirmed,
colour: v.ThemeColour,
church: v.Church.Name,
parishAdminName: v.Admins.AdministratorName,
parishAdminUser: v.Admins.AdminUsername,
parishAdminId: v.Admins.AdministratorId,
fee: v.Fee,
id: v.AppointmentId
});
})
GenerateCalender(events);
},
error: function (error) {
alert("failed");
console.log(error);
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar('refetchEvents');
$('#calender').fullCalendar({
contentHeight: 500,
defaultDate: new Date(),
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
timeFormat: 'HH:mm',
eventLimit: true,
eventColor: events.ThemeColour,
events: events,
eventRender: function (event, element) {
if (event.fee == null) {
if (event.confirmed == false) {
element.css('background-color', '#FF0000');
element.css('border-color', '#FF0000');
}
else {
element.css('background-color', '#008000');
element.css('border-color', '#008000');
}
}
else
{
element.css('background-color', '#0000FF');
element.css('border-color', '#0000FF');
}
},
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #details').text(calEvent.details);
var $details = $('<div/>');
if (calEvent.fee != null) {
$details.append($('<p/>').html('<b>Date of Ceremony : </b>' + calEvent.date.format("DD-MMM-YYYY HH:mm a")));
}
else {
$details.append($('<p/>').html('<b>Date of Appointment : </b>' + calEvent.date.format("DD-MMM-YYYY HH:mm a")));
}
if (calEvent.end != null) {
$details.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$details.append($('<p/>').html('<b>Details : </b>' + calEvent.details));
$details.append($('<p/>').html('<b>Church Name : </b>' + calEvent.church));
if (calEvent.fee == null) {
if (calEvent.room != null) {
$details.append($('<p/>').html('<b>Room : </b>' + calEvent.room));
}
else {
$details.append($('<p/>').html('<b>Room Not Confirmed'));
}
}
$details.append($('<p/>').html('<b>Parish Admin : </b>' + calEvent.parishAdminName));
if (calEvent.confirmed == true)
{
$details.append($('<p/>').html('<b>Status : Confirmed </b>'));
}
else
{
$details.append($('<p/>').html('<b>Status : Not Confirmed </b>'));
}
$('#myModal #pDetails').empty().html($details);
$('#myModal').modal();
}
})
}
})
</script>
}
Your JSON payload is likely being cached by the browser.
To stop this, add this attribute above GetEvents:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = OutputCacheLocation.None)]
to disable caching.
Team,
I am new to jquery and C#. I am trying to integrate jquery Full calendar plugin with the code in C# to show leaves taken up by company resources.There are more than 10,000 records in the database which i would like to filter by fiscal year and fiscal month.So I would like to pass in the two parameters to the C# db code (year and month) when i click on prev and next buttons.
I am able to display the first 500 rows from the db on the calendar( I guess i cannot display more than that--Seems a limitation)
Below is the code
js code
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "CalendarPage.aspx/GetEvents",
dataType: "json",
success: function (data) {
$('div[id*=fullcal]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: $.map(data.d, function (item, i) {
//var eventsUrl = '/events/' + end.year() + '/' + parseInt(end.month());
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.end = new Date(item.EndDate);
event.title = item.EventName;
event.url = item.Url;
event.ImageType = item.ImageType;
return event;
}), eventRender: function (event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
loading: function (bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
$('#loading').hide();
$('div[id*=fullcal]').show();
});
function GetImage(type) {
if (type == 0) {
return "<br/><img src = 'Styles/Images/attendance.png' style='width:24px;height:24px'/><br/>"
}
else if (type == 1) {
return "<br/><img src = 'Styles/Images/not_available.png' style='width:24px;height:24px'/><br/>"
}
else
return "<br/><img src = 'Styles/Images/not_available.png' style='width:24px;height:24px'/><br/>"
}
</script>
C# code
[WebMethod]
public static IList GetEvents()
{
Leave_Management_Leave_TakenTableAdapter LTTA = new Leave_Management_Leave_TakenTableAdapter();
DB.Leave_Management_Leave_TakenDataTable LTTbl = null;
**LTTbl = LTTA.GetForCalendar("I wish to put the parameters here");**
IList events = new List<Event>();
foreach( DataRow dr in LTTbl.Rows)
{
events.Add(new Event
{
EventName = dr["Fullname"] + " Leave",
// DateTime dt = ,
StartDate = DateTime.Parse(dr["leave_days"].ToString()).ToString("MM-dd-yyyy")
});
}
return events;
}
Can anyone please suggest any changes ?
Fullcalendar passes 2 GET parameters anytime it makes a request for data, if you add (DateTime start, DateTime end) to your GetEvents method you can filter your data for the given range.
https://fullcalendar.io/docs/event_data/events_json_feed/
I thought earlier that the control faced a limitation of populating around 700-800 event records on the calendar. On further investigating, I stumbled on a piece of code to be placed in the web.config. This basically maximizes the lenght of jsonserialization string.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
On my View I have a button I use to submit a [description] value to my Controller via JSON, which is then used to create a new Table record. For example:
[HttpPost]
public JsonResult createNewStatus(string description)
{
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
//var allErrors = ModelState.Values.SelectMany(x => x.Errors);
try
{
if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description }, JsonRequestBehavior.AllowGet);
}
What I'd like to do now (before saving the Status to the DB) is run a check to see if any other records in the INV_Statuses table have a [description] value matching the one submitted to the function for new creation. If there is a match, I want to return an error/validation? message and alert the user the submitted value already exists and to choose it from the DropDownList on the View.
Can anyone provide an example of how to go about this with LINQ in my MVC Controller?
EDIT: Added my View JS code for submitting the new Status:
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
},
error: function () {
alert("ERROR!");
}
});
});
EDIT2:
Adricadar's suggestion:
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
try
{
var existingStatus = db.INV_Statuses.FirstOrDefault(x => x.status_description.ToUpper() == status.status_description.ToUpper());
var isDuplicateDescription = existingStatus != null;
if (isDuplicateDescription)
{
ModelState.AddModelError("Error", "[" + status.status_description + "] already exists in the database. Please select from the DropDownList.");
}
else if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description }, JsonRequestBehavior.AllowGet);
I added a .ToUpper() in my comparison in Controller, but even though the match with .ToUpper() gets identified, the ModelState.AddModelError() code fires, then the code returns and no error message is issued?
The value (though duplicate) still gets added to the dropdownlist (visually, not in DB) via my current JS code:
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
},
error: function () {
alert("ERROR!");
}
});
});
Check for existing status and set status back as follows:
var existingStatus = db.INV_Statuses.FirstOrDefault(s => s.status_description == description);
if (existingStatus ==null)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
else
{
// set the status back to existing
status = existingStatus;
}
Set an existing flag in your response:
return Json(new { ID = status.Id, Text = status.status_description, AlreadyExists = (existingStatus != null) }, JsonRequestBehavior.AllowGet);
Then in your response JavaScript, simply parse out the returned data:
success: function (resp) {
if (resp.AlreadyExists != true)
{
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
}
else
{
alert(resp.status_description + " already exists");
$("#selectStatus").val(resp.Id);
}
}
You can query the database for a status with an existing description and if exists and an model state error.
Be aware that string comparison is case sensitive.
[HttpPost]
public JsonResult createNewStatus(string description)
{
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
//var allErrors = ModelState.Values.SelectMany(x => x.Errors);
try
{
var existingStatus = db.INV_Statuses.FirstOrDefault(x => x.status_description.ToUpper() == status.status_description.ToUpper());
var isDuplicateDescription = existingStatus != null;
string error = String.Empty;
if (isDuplicateDescription)
{
error = "[" + status.status_description + "] already exists in the database. Please select from the DropDownList.";
}
else if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description, Error = error , IsDuplicate = isDuplicateDescription }, JsonRequestBehavior.AllowGet);
}
In javascript verify if response have IsDuplicate = true if is true you skip the part where you need to add an element in dropdown.
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
if(resp.IsDuplicate)
{
//display error from response
//display resp.Error
} else {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
}
},
error: function () {
alert("ERROR!");
}
});
});
I have a new development task , I am trying to do reports dashboard and my requirement is to
I will have a form and I need to select values from form and depending upon user selection I need to display high charts in the same page and tabular view of my data in same page. So my form content is static and my Highcharts data and tabular contains dynamic data.
Steps I have done so far:
Login form and if credentials are valid Displays my mainform.aspx
My mainform.aspx contians form with a submit button
<form id="StatsForm" name="StatsForm" action="../Stats/Index/" method="POST"
enctype="multipart/form-data">
<%= Html.AntiForgeryToken()%>
<% Html.RenderPartial("OptionalFields"); %>
</form>
On button click I am sending my form data to controller
//
$(document).ready(function () {
$("#GetReport").click(function () {
$("form[name=StatsForm]").submit();
});
});
//]]>
</script>
I am doing some repository functions from my form data in my controller action and I am adding form values to a model class.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
var manufacturerId = Convert.ToInt32(form["manufacturerId"]);
var reportId = Convert.ToInt32(form["reportId"]);
var categoryId = Convert.ToInt32(form["categoryId"]);
var retailerId = Convert.ToInt32(form["retailerId"]);
var countryId = Convert.ToInt32(form["countryId"]);
var regionId = Convert.ToInt32(form["regionId"]);
var manufacturerWidgetId = (form["ManufacturerWidgetId"]);
var startDate = new DateTime(1, 1, 1, 0, 0, 0, 0);
var endDate = new DateTime(1, 1, 1, 0, 0, 0, 0);
if (!String.IsNullOrEmpty(form["StartDate"]))
{
startDate = Convert.ToDateTime(form["StartDate"]);
}
if (!String.IsNullOrEmpty(form["EndDate"]))
{
endDate = Convert.ToDateTime(form["EndDate"]);
}
var reportName = _reportRepository.GetReport(reportId);
var stats = new Stats
{
ManufacturerId = manufacturerId,
CountryId = countryId,
ReportName = reportName.ToString(),
StartDate = startDate,
EndDate = endDate
};
Now I am struck, I did below steps not sure if I am right. I thought because my mainform.aspx has to display dynamic partials I am trying to create partials foreach report and on selection of uservalue I am planning to inject corresponding partial in my mainform.aspx.
for that I am doing : (continuation of my Action method)
switch (reportName.Code)
{
case "INTER":
return RedirectToAction("InterStats",
new
{
manufacturerId = manufacturerId,
countryId = countryId,
startDate = "2013-01-01",
endDate = "2013-01-31"
});
break;
case "CUMLEADS":
return RedirectToAction("ParametersCumLeads",
new
{
manufacturerId = manufacturerId,
countryId = countryId,
categoryId = categoryId,
startDate = startDate.ToString("yyyy-MM-dd"),
endDate = endDate.ToString("yyyy-MM-dd")
});
break;
case "IMP":
break;
}
5.My partial view:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public JsonResult InterStats(int manufacturerId, int countryId, DateTime startDate, DateTime endDate)
{
//Get all manufacturerwidgets for manufacturer
var manufacturerWidget = _manufacturerWidgetsRepository.GetManufacturerWidgetByManufacturerAndCountry(manufacturerId, countryId);
var interReport = new InterReport();
var interRecordList = new List<InterRecord>(); // a list of my anonymous type without the relationships
interReport.InterRecordList = new List<InterRecord>();
var count = 1;
foreach (var mw in manufacturerWidget)
{
var widgetName = mw.Description;
//Get the product stats data
var imps = _productStatsRepository.GetSumImpressionsProductStatsForManufacturerCountryDate(
mw.Id, countryId, startDate, endDate);
var clicks = _productStatsRepository.GetSumClicksProductStatsForManufacturerCountryDate(
mw.Id, countryId, startDate, endDate);
float ctr = 0;
if (imps != 0 && clicks != 0)
{
ctr = ((clicks / (float)imps) * 100);
}
// Create the data for the report
var interRecord = new InterRecord
{
WidgetName = widgetName,
Impressions = imps,
Interactions = clicks,
Ctr = ctr,
Count = count
};
interReport.InterRecordList.Add(interRecord);
count++;
}
interReport.Counter = count;
return Json(interReport, JsonRequestBehavior.AllowGet);
}
And I tried in my mainform.aspx to write a small ajax function to render partial data , but $("#GetReport").click(function () I am sending form back to controller dont know how it will again here ?
<script type="text/javascript" language="javascript">
//<![CDATA[
$(document).ready(function () {
$("#GetReport").click(function () {
$.ajax({
url: "/Stats/InterStats/<%: Model.ManufacturerId %>/<%: Model.CountryId %>/<%: Model.StartDate %>/<%: Model.EndDate %>",
type: 'get',
success: function (data) {
<% Html.RenderPartial("InterStats"); %>
}
});
$("form[name=StatsForm]").submit();
});
});
//]]>
</script>
So I ahve my partial views, my data ready and I am not able to display corresponding partial in my mianform.aspx .Please help how can I do this?
$.ajax({
url: "/Stats/InterStats/<%: Model.ManufacturerId %>/<%: Model.CountryId %>/<%: Model.StartDate %>/<%: Model.EndDate %>",
type: 'get',
success: function (data) {
<% Html.RenderPartial("InterStats"); %>
}
});
Instead of this, you need some javascript in the success function to handle the response. Probably something like:
success: function (data) {
$('#someDivId').html(data);
}