I'm trying to check if TerminalID already is taken by another model. The Ajax is posting back correctly and error message also can be seen, but the page will not allow me to submit , I only need to check this information while input to display error message and then post anyway . help me please
Model :
public class MoveModel
{
[Required]
[Remote("CheckExistTrm", "MoveModel")]
public int TerminalID { get; set; }
public string User { get; set; }
........
}
Controller:
public JsonResult CheckExistTrm(int TerminalID)
{
var terminal = db.Terminals.Find(TerminalID);
if (terminal == null)
return null;
var agrdet = (from t in db.AgreementDetails where (t.TerminalID == terminal.TerminalID && t.Condition == "New") select t).FirstOrDefault();
if (agrdet != null)
{
var agreement = db.Agreements.Find(agrdet.AgreementID);
return Json("consider! this terminal is active in the agreement: " + agreement.AgreementNumber ,JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
View (I am using devexpress ):
#using (Html.BeginForm("CreateAndEdit", "MoveModel", FormMethod.Post, new { #class = "edit_form" })){
#Html.AntiForgeryToken()
#Html.Hidden("MoveModelID")
<div class="line">
#Html.DevExpress().Label(
settings =>
{
settings.ControlStyle.CssClass = "label";
settings.AssociatedControlName = "TerminalID";
settings.Text = "ტემრინალი";
}
).GetHtml()
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "TerminalID";
settings.ControlStyle.CssClass = "editor";
settings.Properties.TextField = "Name";
settings.Properties.ValueField = "TerminalID";
settings.Properties.ValueType = typeof(int);
settings.Properties.DropDownStyle = DropDownStyle.DropDown;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
}
).BindList(LeaseReg.Models.Terminal.getTerminals()).Bind(Model.TerminalID).GetHtml()
#Html.ValidationMessageFor(model => model.TerminalID,null, new { #class = "validator" })
</div>
<div class="line">
#Html.DevExpress().Label(
settings =>
{
settings.ControlStyle.CssClass = "label";
}
).GetHtml()
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnUpdate";
settings.ControlStyle.CssClass = "button";
settings.Text = "დადასტურება";
settings.UseSubmitBehavior = true;
}
).GetHtml()
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnCancel";
settings.ControlStyle.CssClass = "button"; ;
settings.Text = "გაუქმება";
settings.ClientSideEvents.Click = "function(s, e){ document.location='" + DevExpressHelper.GetUrl(new { Controller = "MoveModel", Action = "Index" }) + "'; }";
}
).GetHtml()
</div>
#Html.ValidationSummary(true);}
Related
I'm trying to upload an image using an API but the same error shows every time:
"Error reading bytes. Unexpected token: StartObject. Path 'picture'"
the picture is declared as a byte[] in the ASP.NET entity
and I use the formdata to post the picture in angular
Angular code:
onFileChanged(event) {
this.selectedFile = event.target.files[0]
}
adduser() {
this.fd = new FormData();
this.fd.append('picture', this.selectedFile)
this.user.firstname = this.firstname;
this.user.lastname = this.lastname;
this.user.password = this.pass;
this.user.userName = this.email;
this.user.type = this.role;
this.user.picture = this.fd;
alert(this.user.picture)
this.auth.adduser(this.user).subscribe(Response => {
console.log(Response);
this.route.navigate(['login']);
}, error => {
console.log(error)
});
}
.Net code:
[HttpPost]
public async Task < Object > PostAdmin([FromBody] UserModel model) {
{
var profile = new Profile() {
UserName = model.UserName,
lastname = model.lastname,
address = model.address,
firstname = model.firstname,
picture = model.picture,
phone = model.phone,
university = model.university,
Type = model.Type
};
using(var stream = new MemoryStream()) {
profile.picture = stream.ToArray();
}
var user = await _userManager.FindByNameAsync(profile.UserName);
if (user != null) {
return Ok(new {
status = false
});
}
try {
var result = await _userManager.CreateAsync(profile, model.Password);
var role = await _userManager.AddToRoleAsync(profile, model.Type);
return Ok(result);
}
catch (Exception e) {
return BadRequest(new {
status = false, message = e.Message
});
}
This is my property
[Remote("IsUserAlreadyExist","Admin",AdditionalFields="User_Id,NT_Login_Name",ErrorMessage=Constants.ErrorMessage.UserAlreadyExists)]
public string NT_Login_Name { get; set; }
And the action method looks like :-
public JsonResult IsUserAlreadyExist(UserModel umodel)
{
CommonAdapter commonAdapter = new CommonAdapter();
Dictionary<string, object> spParameters = new Dictionary<string, object>();
spParameters.Add("inNTLogin", umodel.NT_Login_Name);
DataSet userdetails = commonAdapter.ExecuteSP(Constants.SPName.GetUserByNTLogin, spParameters);
if (userdetails != null)
{
if (userdetails.Tables[0].Rows.Count > 0)
{
if (umodel.User_Id > 0)
{
umodel.IsUserExists = true;
}
else
{
umodel.IsUserExists = false;
}
}
else
{
IsUserOnLDAP(umodel);
umodel.IsUserExists = true;
}
}
return Json(umodel,JsonRequestBehavior.AllowGet);
}
The model returning correct values but its not binding in the textbox on my view like this
<td class="tds">
#Html.TextBoxFor(x => x.NT_Login_Name, new { #id = "txtNT", #class = "txtbox" })
#Html.ValidationMessageFor(x => x.NT_Login_Name, "", new { #class = "errormessage", #validationgroup = "btnSubmit" })
</td>
The purpose of Remote attribute is do some action and return either boolean or string in json format
But in your case you are returning a model
return Json(umodel,JsonRequestBehavior.AllowGet);
I guess you have to modify your code to return
return Json(true, JsonRequestBehavior.AllowGet);
if the the validation succeeds and
return Json("Some String", JsonRequestBehavior.AllowGet);
if the validation fails.
Something like this
public JsonResult IsUserAlreadyExist(UserModel umodel)
{
CommonAdapter commonAdapter = new CommonAdapter();
Dictionary<string, object> spParameters = new Dictionary<string, object>();
spParameters.Add("inNTLogin", umodel.NT_Login_Name);
DataSet userdetails = commonAdapter.ExecuteSP(Constants.SPName.GetUserByNTLogin, spParameters);
if (userdetails != null)
{
if (userdetails.Tables[0].Rows.Count > 0)
{
if (umodel.User_Id > 0)
{
//umodel.IsUserExists = true;
return Json(false,JsonRequestBehavior.AllowGet);
}
else
{
//umodel.IsUserExists = false;
return Json(true,JsonRequestBehavior.AllowGet);
}
}
else
{
//IsUserOnLDAP(umodel);
//umodel.IsUserExists = true;
return Json(!IsUserOnLDAP(umodel),JsonRequestBehavior.AllowGet);
}
}
return Json(false,JsonRequestBehavior.AllowGet);
}
I have a webpage with gridview from Devexpress and i've implemented export to pdf. But somehow I don't get the current filter, order or group setting. I'm wondering if there is something wrong with how i set my setting in code or something since I've googled a lot at seems like those options should be handled automatically in ExportToPdf as long as you have rigth setting. My _GripPartial.cshtml:
#Html.DevExpress().GridView(TreeMenuTest.Controllers.LogViewController.GridViewSettings).Bind(TreeMenuTest.Controllers.LogViewController.DataSource).GetHtml()
_LogView.cshtml:
#using (Html.BeginForm("ExportToPDF", "LogView", FormMethod.Post))
{
<div id="buttonExport" class ="gridBtn">
<input type="submit" id ="ExportBtn" value="Export to pdf" />
</div>}
<div id="buttonReset" class ="gridBtn">
<input type="button" id ="ResetBtn" value="Reset Grid" onclick="javascript: ResetGrid()"/>
</div>
#Html.Action("Grid","LogView")
And finally LogViewController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using TreeMenuTest.Models;
using DevExpress.Web.Mvc;
using DevExpress.Web.ASPxGridView;
using System.Globalization;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxClasses;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using System.IO;
using System.Drawing.Printing;
namespace TreeMenuTest.Controllers
{
public class LogViewController : Controller
{
//
// GET: /LogView/
public static List<LoggingEvent> DataSource;
static GridViewSettings exportGridViewSettings;
public static GridViewSettings GridViewSettings
{
get
{
if (exportGridViewSettings == null)
exportGridViewSettings = GetGridViewSettings();
return exportGridViewSettings;
}
}
static GridViewSettings GetGridViewSettings()
{
GridViewSettings settings = new GridViewSettings();
settings.Name = "GridView";
settings.CallbackRouteValues = new { Controller = "LogView", Action = "Grid" };
settings.Width = Unit.Percentage(100);
settings.Theme = "BlackGlass";
settings.KeyFieldName = "Id";
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.SettingsPager.PageSize = 25;
settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;
settings.Settings.ShowHeaderFilterButton = true;
settings.SettingsPopup.HeaderFilter.Height = 200;
settings.SettingsExport.Landscape = true;
settings.SettingsExport.TopMargin = 0;
settings.SettingsExport.LeftMargin = 0;
settings.SettingsExport.RightMargin = 0;
settings.SettingsExport.BottomMargin = 0;
settings.SettingsExport.PaperKind = PaperKind.A4;
settings.SettingsExport.RenderBrick = (sender, e) =>
{
if (e.RowType == GridViewRowType.Data && e.VisibleIndex % 2 == 0)
e.BrickStyle.BackColor = System.Drawing.Color.FromArgb(0xEE, 0xEE, 0xEE);
};
settings.Columns.Add("Id");
settings.Columns.Add(column =>
{
column.FieldName = "Ts";
column.Settings.AutoFilterCondition = AutoFilterCondition.Like;
});
settings.Columns.Add("LogLevelText").Caption = "Level";
settings.Columns.Add("LoggerName");
settings.Columns.Add("Message");
settings.Columns.Add("ThreadName").Caption = "Thread";
settings.Columns.Add("UserName");
settings.Columns.Add("Domain");
settings.Columns.Add("ClassName");
settings.Columns.Add("FileName");
settings.Columns.Add("MethodName").Caption = "Method";
settings.Columns.Add("LineNumber").Caption = "Line";
settings.Columns.Add("LocalIP");
settings.Columns.Add("MachineName").Caption = "Machine";
settings.Columns.Add("UnikeName");
settings.Settings.ShowPreview = true;
settings.PreviewFieldName = "ExceptionString";
return settings;
}
public ActionResult Index()
{
return PartialView("_LogView");
}
public ActionResult Grid()
{
if (DataSource == null)
{
DataSource = GetAllEventsLast24h();
}
return PartialView("_GridPartial");
}
public ActionResult EmptyGrid()
{
DataSource = null;
return PartialView("_GridPartial");
}
public List<LoggingEvent> GetAllEventsLast24h() {
return GetEventsWithCommand("where Ts > '" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss") + "';");
}
public List<LoggingEvent> GetEventsOnDateTime(DateTime fromDate, DateTime toDate)
{
return GetEventsWithCommand("where Ts > '" + fromDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND Ts < '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "';");
}
public List<LoggingEvent> GetEventsWithCommand(string where)
{
List<LoggingEvent> events = new List<LoggingEvent>();
SqlConnection myConnection = new SqlConnection("Data Source=xxx;user id=xxx;password=xxx;connection timeout=30");
myConnection.Open();
SqlDataReader myReader = null;
SqlCommand command = new SqlCommand("SELECT Id,Ts,LogLevel,LoggerName,Message,ThreadName,UserName,ExceptionString,Domain,ClassName,FileName,MethodName,LineNumber,LocalIP,MachinName,UnikeName from dbo.LoggingEvent " + where);
command.Connection = myConnection;
myReader = command.ExecuteReader();
while (myReader.Read())
{
events.Add(LoggingEvent.ReadEntityFromDbReader(myReader));
}
myConnection.Close();
return events;
}
[HttpPost]
public ActionResult ReloadGrid(string fromDate, string toDate)
{
DateTime fromDateTime;
DateTime toDateTime;
if (!string.IsNullOrEmpty(fromDate) && !string.IsNullOrEmpty(toDate)) // todo
{
fromDateTime = ParseStringToDate(fromDate);
toDateTime = ParseStringToDate(toDate);
}
else// No dates specified = get last 24 hours
{
toDateTime = DateTime.Now;
fromDateTime = toDateTime.AddHours(-24);
}
if (fromDateTime.CompareTo(toDateTime) > 0)
{
// from date grater then todate, change places
DateTime temp = toDateTime;
toDateTime = fromDateTime;
fromDateTime = temp;
}
DataSource = GetEventsOnDateTime(fromDateTime, toDateTime);
return PartialView("_LogView");
}
public DateTime ParseStringToDate(string datetxt)// todo this is copy froim treemenuviewcontroller, create utilsclass
{
const string dateformat = "dd.MM.yyyy HH:mm"; // jquery datepicker
const string dateformat2 = "yyyy-MM-dd HH:mm";// chrome TODO different formats with different location setting?
DateTime dateTime;
try //todo error handling!
{
dateTime = DateTime.ParseExact(datetxt, dateformat, CultureInfo.InvariantCulture);
}
catch
{
dateTime = DateTime.ParseExact(datetxt, dateformat2, CultureInfo.InvariantCulture);
}
return dateTime;
}
public ActionResult ExportToPDF()
{
var printable = GridViewExtension.CreatePrintableObject(GridViewSettings, DataSource);
PrintingSystem ps = new PrintingSystem();
PrintableComponentLink link1 = new PrintableComponentLink(ps);
link1.Component = printable;
link1.PrintingSystem.Document.AutoFitToPagesWidth = 1;
link1.Landscape = true;
CompositeLink compositeLink = new CompositeLink(ps);
compositeLink.Links.Add(link1);
compositeLink.CreateDocument();
using (MemoryStream stream = new MemoryStream())
{
compositeLink.PrintingSystem.ExportToPdf(stream);
WriteToResponse("filename", true, "pdf", stream);
}
ps.Dispose();
return Index();
}
void WriteToResponse(string fileName, bool saveAsFile, string fileFormat, MemoryStream stream)
{
string disposition = saveAsFile ? "attachment" : "inline";
Response.Clear();
Response.Buffer = false;
Response.AppendHeader("Content-Type", string.Format("application/{0}", fileFormat));
Response.AppendHeader("Content-Transfer-Encoding", "binary");
Response.AppendHeader("Content-Disposition",
string.Format("{0}; filename={1}.{2}", disposition, fileName, fileFormat));
Response.BinaryWrite(stream.GetBuffer());
Response.End();
}
}
}
Any clues?
Ps. Asking me why I don't write to DevExpress support is not helpful, so please just don't comment at all.
Check the How to export GridView rows and keep end-user modifications (such as sorting, grouping, filtering, selection) KB Article and make sure if all the steps are implemented.
After help for #Mikhail i fix the issue by putting #Html.Action("Grid","LogView") in the Html.BeginForm in _Log.View.cshtml like that:
<div id="buttonReset" class ="gridBtn">
<input type="button" id ="ResetBtn" value="Reset Grid" onclick="javascript: ResetGrid()"/>
</div>
#using (Html.BeginForm("ExportToPDF", "LogView", FormMethod.Post))
{
<div id="buttonExport" class ="gridBtn">
<input type="submit" id ="ExportBtn" value="Export to pdf" />
</div>
#Html.Action("Grid","LogView")}
I encountered a problem with popup control inside modal edit form of the gridview.
the problem is: popup control won't hide when i click on modal form context area! it just reordered.
please see attached movie first then read the code.
thanks.
here is my code:
MODEL:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public int Avg { get; set; }
}
CONTROLLER:
public class HomeController : Controller
{
public ActionResult Index()
{
Session["Students"] = new List<Student>()
{
new Student { Id = 1, Name = "N1", Family = "f1", Avg = 1 } ,
new Student { Id = 2, Name = "N2", Family = "f2", Avg = 2 } ,
new Student { Id = 3, Name = "N3", Family = "f3", Avg = 3 } ,
new Student { Id = 4, Name = "N4", Family = "f4", Avg = 4 } ,
};
return View(Session["Students"]);
}
public ActionResult PartialGridView(Student student)
{
return PartialView("Index", Session["Students"]);
}
}
View
#model List<Test.Models.Student>
#Html.DevExpress().GridView(settings =>
{
settings.Name = "GvStudent";
settings.KeyFieldName = "Id";
settings.CallbackRouteValues = new { Controller = "Home", Action = "PartialGridView" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "AddStudentPartialGridView" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "UpdateStudentPartialGridView" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "DeleteStudentPartialGridView" };
settings.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm;
settings.SettingsPopup.EditForm.Modal = true;
settings.SettingsPopup.EditForm.HorizontalAlign = PopupHorizontalAlign.WindowCenter;
settings.SettingsPopup.EditForm.VerticalAlign = PopupVerticalAlign.WindowCenter;
settings.SettingsPopup.EditForm.Width = 400;
settings.SettingsPopup.EditForm.Height = 200;
settings.SettingsText.PopupEditFormCaption = "Student";
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.Columns.Add(Name =>
{
Name.FieldName = "Name";
});
settings.Columns.Add(Family =>
{
Family.FieldName = "Family";
});
settings.Columns.Add(Avg =>
{
Avg.FieldName = "Avg";
});
settings.SetEditFormTemplateContent(content =>
{
Html.DevExpress().Button(btnShow =>
{
btnShow.Name="btnShow";
btnShow.ClientSideEvents.Click = "function(s, e){popupControl.ShowAtElement(document.getElementById(s.name));}";
}).Render();
});
}).Bind(Model).GetHtml()
#{
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "popupControl";
settings.CloseAction = CloseAction.OuterMouseClick;
settings.PopupVerticalAlign = PopupVerticalAlign.Below;
settings.PopupHorizontalAlign = PopupHorizontalAlign.LeftSides;
settings.ShowHeader = false;
settings.ShowFooter = false;
settings.AllowDragging = false;
settings.AutoUpdatePosition = true;
settings.Width = 320;
settings.SetContent(() =>
{
ViewContext.Writer.Write("hello world!");
});
}).GetHtml();
}
I have following code for Custom Ajax Binding. This has following problems even though it is displaying data for the first page.
• The request.Sorts is coming as NULL in to the Orders_Read method
• The request.PageSize is coming as 0 to the Orders_Read method
• The request.Page is coming as 1 to the Orders_Read method (even if I click on the page 2)
What changes need to be done here to get proper sort and pagesize values?
Note: I am using MVC Wrapper for Kendo Grid.
VIEW
#Scripts.Render("~/bundles/jquery")
<script type ="text/javascript">
$(document).ready(function (){
$('#Submit1').click(function () {
alert('1');
$('#grid12').data('kendoGrid').dataSource.read();
});
});
</script>
#model KendoPratapSampleMVCApp.Models.Sample
#{
ViewBag.Title = "CustomAjaxbind";
}
<h2>CustomAjaxbind</h2>
#using (Html.BeginForm("PostValues", "CustomAjaxBinding", FormMethod.Post))
{
<input id="Submit1" type="button" value="SubmitValue" />
#(Html.Kendo().Grid<KendoPratapSampleMVCApp.Models.Sample>()
.Name("grid12")
.EnableCustomBinding(true)
.Columns(columns => {
columns.Bound(p => p.SampleDescription).Filterable(false).Width(100);
columns.Bound(p => p.SampleCode).Filterable(false).Width(100);
columns.Bound(p => p.SampleItems).Filterable(false).Width(100);
})
.Pageable()
.Sortable()
.Scrollable()
.AutoBind(false)
.Filterable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(2)
.Read(read => read.Action("Orders_Read", "CustomAjaxBinding"))
)
)
}
Controller
public class CustomAjaxBindingController : Controller
{
//
// GET: /CustomAjaxBinding/
public ActionResult Index()
{
return View("CustomAjaxbind");
}
public ActionResult Orders_Read([DataSourceRequest(Prefix = "grid12")]DataSourceRequest request)
{
string sortField = "SampleDescription";
string sortDirection = string.Empty;
if (request.Sorts != null)
{
foreach (SortDescriptor sortDescriptor in request.Sorts)
{
sortField = sortDescriptor.Member;
if (sortDescriptor.SortDirection == ListSortDirection.Ascending)
{
sortDirection = "Ascending";
}
else
{
sortDirection = "Descending";
}
}
}
int total = 1;
int myPageSize = 2;
if(request.PageSize !=0)
{
myPageSize = request.PageSize;
}
IEnumerable<Sample> currentSamples = GetSubsetEmployees(request.Page - 1, myPageSize, out total, sortField, sortDirection);
var result = new DataSourceResult()
{
Data = currentSamples,
Total = total // Total number of records
};
return Json(result);
}
public IEnumerable<Sample> GetSubsetEmployees(int pageIndex, int pageSize, out int itemCount, string sortField, string sortDirection)
{
IEnumerable<Sample> samples = GetSamples();
itemCount = samples.ToList().Count;
var selector = new Func<Sample, object>(e => e.GetType().GetProperty(sortField).GetValue(e, null));
var query = sortDirection.Equals("descending", StringComparison.OrdinalIgnoreCase)
? samples.OrderByDescending(selector)
: samples.OrderBy(selector);
List<Sample> currentPageEmployees = query
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
return currentPageEmployees;
}
public static IEnumerable<Sample> GetSamples()
{
List<Sample> sampleAdd = new List<Sample>();
Sample s12 = new Sample();
s12.SampleCode = "1";
s12.SampleDescription = "A";
s12.SampleItems = "newone";
Sample s2 = new Sample();
s2.SampleCode = "2";
s2.SampleDescription = "B";
s2.SampleItems = "oldone";
Sample s3 = new Sample();
s3.SampleCode = "3";
s3.SampleDescription = "C";
s3.SampleItems = "latestone";
Sample s4 = new Sample();
s4.SampleCode = "4";
s4.SampleDescription = "D";
s4.SampleItems = "latestoneitem";
sampleAdd.Add(s12);
sampleAdd.Add(s2);
sampleAdd.Add(s3);
sampleAdd.Add(s4);
return sampleAdd;
}
}
Model
namespace KendoUIMvcSample.Models
{
public class SampleModel
{
public List<Sample> samples;
}
public class Sample
{
public string SampleDescription { get; set; }
public string SampleCode { get; set; }
public string SampleItems { get; set; }
}
}
I had the same problem as yours and finally found the solution recently after consuming days on investigating the problem. I post it here if someone else faced the same issue.
You need to remove Prefix from your parameter:
public ActionResult Orders_Read([DataSourceRequest(Prefix = "grid12")]DataSourceRequest request)
Converted to:
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
I don't know if this is a bug from Kendo or not! But in this scenario grid can't be found by Prefix defined.
You can find an example here