bind data dynamically dhtmlx calendar mvc - asp.net-mvc

I currently using DHTMLX calendar in my application with MVC.
Now i load all events by default as follows :
public ActionResult Index()
{
var scheduler = new DHXScheduler(this);
scheduler.LoadData = true;
scheduler.EnableDataprocessor = true;
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
return View(scheduler);
}
/* public ContentResult Data()
{
var data = new SchedulerAjaxData(new TimesheetEventDataContext().Events);
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
return (ContentResult)data;
}*/
public ContentResult Data(int UserId)
{
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
if (UserId != null)
{
var data = new SchedulerAjaxData(new TimesheetEventDataContext().Events.Where(a => a.CreatedBy == UserId.ToString()));
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
return (ContentResult)data;
}
else
{
var data = new SchedulerAjaxData(new TimesheetEventDataContext().Events.Where(a => a.CreatedBy == Session["EmpId"].ToString()));
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
return (ContentResult)data;
}
}
Now i want to load the data by selection user in dropdownlist. So, i pass the userid to controller to fetch the events created by that particualar user.
My view page is following :
<!DOCTYPE html>
<html>
<head>
<title>Timesheet Events</title>
<style>
body
{
background-color:#eee;
}
</style>
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#ddlUsers').change(function () {
emId = $(this).val();
window.location.href = "/Calendar/Data?UserId=" + emId;
});
});
</script>
</head>
<body>
<div style="height:700px;width:900px;margin:0 auto;padding-top:10%;">
<table>
<tr>
<td>
Select User :
</td>
<td style="width:30%;">
#Html.DropDownList("EmpId", null, "-- Choose --", new { #class = "form-control", id = "ddlUsers" })
</td>
<td colspan="10">
<div id="calendar"></div>
</td>
</tr>
</table>
#Html.Raw(Model.Render())
</div>
</body>
</html>
Now, when i select user it pass the id to controller but not load the calendar view based on that..
can anyone help me to do this..
Thanks in advance..

I think what your #ddlUsers handler does is navigates browser to Data action, which is not what you need.
Try reloading data using client-side API of dhtmlxScheduler
$('#ddlUsers').change(function () {
var emId = $(this).val();
scheduler.clearAll();
scheduler.load("/Calendar/Data?UserId=" + emId;, "json");
});
Related docs:
http://docs.dhtmlx.com/scheduler/api__scheduler_clearall.html
http://docs.dhtmlx.com/scheduler/api__scheduler_load.html

Related

Partial view won't render after ajax call

I need to pass list of Objects. I am passing the data threw ajax call, ajax returns the results as expected, so the ajax call gets the correct results but partial view won't render.
Controller
[HttpPost]
public ActionResult GetXlFile()
{
List<ListMatchDetails> lstPreview = new List<ListMatchDetails>();
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var xlFile = System.Web.HttpContext.Current.Request.Files["FileToPreview"];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(xlFile);
if (null != filebase && filebase.ContentLength > 0)
{
if (String.Compare(filebase.ContentType, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
using (Stream stream = filebase.InputStream)
{
IExcelDataReader reader = null;
if (filebase.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (filebase.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
reader.IsFirstRowAsColumnNames = true;
DataSet dsResult = reader.AsDataSet();
DataTable dtResult = dsResult.Tables[0];
if (dtResult.Rows.Count > 0)
{
foreach (DataRow dr in dtResult.Rows)
{
ListMatchDetails lmd = new ListMatchDetails();
lmd.FirstName = (dr[0] != DBNull.Value) ? dr[0].ToString() : string.Empty;
lmd.LastName = (dr[1] != DBNull.Value) ? dr[0].ToString() : string.Empty;
lstPreview.Add(lmd);
}
}
reader.Close();
}
}
}
}
return PartialView("_ExcelGrid", lstPreview);
}
view
#using app.Models;
#model IEnumerable<ListMatchDetails>
#{
if (Model.Count() > 0)
{
ListMatchDetails row = Model.FirstOrDefault();
<table class="table table-hover table-responsive scrollable table-striped ">
<thead id="tableHeader">
<tr>
<td>
#Html.LabelFor(x => row.FirstName)
</td>
<td>
#Html.LabelFor(x => row.LastName)
</td>
</tr>
</thead>
<tbody class="pre-scrollable">
#foreach (var record in Model)
{
<tr>
<td>
#Html.ValueForModel(record.FirstName)
</td>
<td>
#Html.ValueForModel(record.LastName)
</td>
</tr>
}
</tbody>
</table>
}
}
jquery:
$('#btnPreview').click(function () {
var formData = new FormData();
var files = $("#btnbrowse").get(0).files;
if (files.length > 0) { formData.append("FileToPreview", files[0]); }
$.ajax({
url: '/ListMatch/GetXlFile',
type: 'POST',
dataType: 'json',
data: formData,
processData: false,
contentType: false,
success: function (result) {
//$('#record').html(result)
$('._ExcelGrid').json(result);
},
error: function () {
//alert('Click Called');
}
});
});
Right off the bat comparing your action method to your jQuery ajax call, it looks like you're trying to parse the result of the ajax call as a JSON string but you're returning the _ExcelGrid partial view. Unless the _ExcelGrid partial view is returning valid JSON, that's going to break when it attempts to parse it as JSON.
I can't tell how it's supposed to be because I'm not sure what ._ExcelGrid is in your view, but generally speaking you can either change the action method to return JSON instead of a partial view and then parse/handle the JSON on the client side or assign the returned partial view to the element with $("._ExcelGrid").html(result). Which way you handle it is up to you.
If you opt to return the partial view, for completionist sake I'd change the dataType in your ajax call to html, because you're not expecting JSON anymore. You probably also want to set the contentType to the type of content that you're sending to the server, you can occasionally run into funny errors if you're not explict.
it looks like you need to use $('#record').html(result). Make sure you have something like
<div id="record">
</div>
This will get you past your roadblock. Please let me know if you want me to add more code pertaining to your question.
_ExcelGrid.cshtml
A Partial View
Controller:
public class HomeController : Controller
{
[HttpPost]
public PartialViewResult GetXlFile()
{
return PartialView("_ExcelGrid");
}
public ActionResult GetXlFile(int? id)
{
return View();
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
#*credit to
https://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor*#
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index800</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$('form').submit(function (event) {
$.ajax({
url: this.action,
type: "POST",
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
return false;
});
});
</script>
</head>
<body>
<form>
<div>
#using (Html.BeginForm())
{
<input type="submit" value="OK" />
}
<div id="result"></div>
</div>
</form>
</body>
</html>
Greet for the day !!
Have you defined the partial view on your main page? if not you need to define partial view on your main page just like
<div id="dvExcelGrid">
#Html.Partial("_ExcelGrid", "your model")
</div>

how to get ID from URL in asp.net MVC controller

I want to get the ID from URL in ASP.NET MVC Controller and insert it into Project_ID, the bellow is my code, i tried but its now working for me.
http://localhost:20487/ProjectComponent/Index/1
My Controller
[HttpPost]
public JsonResult SaveComponent(OrderVM O, int id)
{
bool status = false;
if (ModelState.IsValid)
{
using (Entities db = new Entities())
{
ProjComponent ProjComponent = new ProjComponent { project_id = id, title = O.title, description = O.description };
foreach (var i in O.ProjComponentActivities)
{
ProjComponent.ProjComponentActivity.Add(i);
}
db.ProjComponents.Add(ProjComponent);
db.SaveChanges();
status = true;
}
}
}
You can always use a hidden field and update it by jquery/javscript and send it to back end in ajax helper.....
Make sure 1.name should be exactly name as ActionMethod param and 3.Jquery ,jQuery Validate and jQuery unobstrusive ajax is loaded correctly
My code .cshtml
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div>
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.OnBegin = "OnBeginRequest";
options.OnSuccess = "OnSuccessRequest";
options.OnComplete = "OnCompleteRequest";
options.OnFailure = "OnFailureRequest";
// options.Confirm = "Do you want to Add Country ?";
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
#using (Ajax.BeginForm("AjaxSend", "Stackoverflow", options))
{
<input type="hidden" name="project_id" id="project_id" value="project_id" />
<input type="submit" value="Click me" />
}
</div>
<div id="divResponse">
</div>
<script>
$(function() {
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length - 1];
console.log(lastsegment);
$('#project_id').val(lastsegment);
});
function OnBeginRequest() {
console.log('On Begin');
}
function OnCompleteRequest() {
console.log('On Completed');
}
function OnSuccessRequest() {
console.log('On Success');
}
function OnFailureRequest() {
console.log('On Failure');
}
</script>
and Controller
[HttpPost]
public JsonResult AjaxSend(String project_id)
{
//rest goes here
return Json(new { Success = true });
}
this link may help link
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable

How to display two views using two different models on the same web page in ASP.NET MVC

Here is the code for controllers and view. I want to display the both views on the same webpage in ASP.NET MVC. How to achieve this goal?
Controller:
public ActionResult LetterList()
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return View(obj);
}
public ActionResult Showimage(string ListId)
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return View(letterList);
}
View Of LetterList
#model LetterPage.Models.ModelView
<div>
#{
foreach (var item in Model.letterDetail)
{
<div>
#item.ListName
</div>
}
}
</div>
ShowImage view:
#model IList< LetterPage.Models.hurf_e_tahaji>
#{
ViewBag.Title = "ShowImage";
}
<table class="table">
<tr>
<th>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<img src="#Url.Content("item.Letter_Pic") "/>
</td>
</tr>
}
</table>
When I created these views as partial views and render them into another view exception occurs on the Foreach loop at model.
You can use PartialView:
[HttpPost]
public PartialViewResult LetterList()
{
if (Request.IsAjaxRequest())
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return PartialView(obj);
}
return null;
}
[HttpPost]
public PartialViewResult Showimage(string ListId)
{
if (Request.IsAjaxRequest())
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return PartialView(letterList);
}
return null;
}
Then you have to define your partial views (like code you posted), And inside the main view:
<div class="LetterList">
<img src="#Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
<div class="Showimage">
<img src="#Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$.post('/Home/LetterList', function(data) {
$('.LetterList').html(data);
});
$.post('/Home/Showimage/' + ListId, function(data) {
$('.Showimage').html(data);
});
});
</script>
}

MVC 5 view not autoupdating partial view

I have a controller
public class AccountDetailsController : Controller
{
private readonly IAccountStatsRepository _accountStatsRepository;
public AccountDetailsController(IAccountStatsRepository accountStatsRepository)
{
_accountStatsRepository = accountStatsRepository;
}
public ActionResult Details(string accountEmail)
{
var stats = _accountStatsRepository.Get(accountEmail);
var accountDetailsViewModel = new AccountDetailsViewModel
{
Email = accountEmail,
Money = stats.TotalCredits
};
return View(accountDetailsViewModel);
}
[OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)] // every 3 sec
public ActionResult GetLatestLogging(string email)
{
//if (email == null || email != null)
//{
var list = new List<LogViewModel>();
return PartialView("LatestLoggingView", list);
//}
}
}
And a View
#using FutWebFrontend.ViewModels
#model AccountDetailsViewModel
#{
ViewBag.Title = "Details";
}
<h2>#Model.Email</h2>
<div>
<h4>Account details</h4>
Money #String.Format("{0:0,0}", Model.Money)
</div>
<div id="loggingstream">
#Html.Partial("LatestLoggingView", new List<LogViewModel>())
</div>
<hr />
<dl class="dl-horizontal"></dl>
<p>
#Html.ActionLink("Back to List", "index", "AccountControl")
</p>
<script type="text/javascript">
$(function() {
setInterval(function () { $('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});
</script>
But when I go to my page and put a breakpoint in GetLatestLogging then nothing happens
If I hit F12 in chrome I get "Uncaught ReferenceError: $ is not defined "Details:67
From what I can gather, this should hit my Get method every 3 seconds, but I must have made a simple error somewhere
Try this
$( document ).ready(function() {
setInterval(function () {$('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});

DropDown change show partial

I have used from dropdownlist in page.
I want, when change selected id info, load bottom of page.
first time that page load is true,but with dropdown change load info in new page, not part of current page.
Fill dropdown list
public ActionResult selVahedList(int IdType, int IdChoose)
{
ViewBag.ChooseItem = IdChoose;
IEnumerable<Lcity> Lcitys = Dbcon.Lcitys;
var model = new CityViewMode
{
Lcitys = Lcitys.Select(x => new SelectListItem
{
Value = x.Citycode.ToString(),
Text = x.CityName
})
};
return View(model);
});
Partial view shows after dropdown changed
public ActionResult selVahedListAjax(CityViewMode model)
{
int idcity=Convert.ToInt32(model.SelectedCitycode);
// int idcity = 1;
ViewBag.Reshteh = 1;
//string IdCity = base.Request["SelValue"].ToString();
var res = Dbcon.TaavoniInfos.Where(m => m.IDReshteh == 1 && m.Citycode ==idcity);
return PartialView("selVahedListAjax", res);
}
view page
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "LoadData",
LoadingElementId="loadAdmin"
};
#using (Ajax.BeginForm("selVahedListAjax",ajaxOpts))
{
<fieldset>
<div class="PContent">
<p class="DroplistCity" id="DroplistCity">
#Html.DropDownListFor(
x => x.SelectedCitycode,
new SelectList(Model.Lcitys, "Value", "Text",""))
<div id="LoadData">
#Html.Action("selVahedListAjax", new { IdReshte = ViewBag.ChooseItem })
</div>
</div>
</fieldset>
}
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#SelectedCitycode').change(function () {
this.form.submit();
});
});
</script>
thanks for your help
my partial view code is: #model
IEnumerable<TaavonS.Models.TaavoniInfo>
<ul>
#foreach (var item in Model)
{
<li>:<b>#Html.DisplayFor(modelItem => item.SName)</b></li>
<li>:<b>#Html.DisplayFor(modelItem => item.ModirName)</b></li>
<li><img src="#Url.Content("~/Content/img/list16.png")" alt=""/>
#Html.ActionLink("detail....", "Detaild",new { codef= item.Scode }, new { #class = "openDialog", data_dialog_id = "emailDialog", data_dialog_title = "" } )
<hr class="separatorLine"/></li> when i load page is true but after dropdownlist is nt work
<li>
#if (!string.IsNullOrEmpty(item.TablighatPic))
{
<img src="#Url.Content("~/Content/img/eye.png")"/> #Html.ActionLink("تبلیغات....", "showImg", new { code = item.Scode }, new { #class = "openImg", data_dialog_id = "mailDialog" })<hr class="separatorLine"/>
}
</li>
}
</ul>
I think you need to change your ajaxOptions:
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "LoadData",
LoadingElementId="loadAdmin",
InsertionMode = InsertionMode.Replace // add this line
};
Add the parameter to the beginForm call
#using (Ajax.BeginForm("selVahedListAjax",
new { IdReshte = ViewBag.ChooseItem }, //add this to the Ajax.BeginForm call
ajaxOpts ))
{
and remove this line from the target div if you don't want the ajax call performed before the user chooses anything
#Html.Action("selVahedListAjax", new { IdReshte = ViewBag.ChooseItem })

Resources