Now i am using Kendo for Autocomplete text. Database is Northwind. But it always return undefined. I don't know to have any wrong thing?
View
#(Html.Kendo().AutoComplete()
.Name("cbRegion")
.Filter("contains")
.DataTextField("RegionDescription"))
.DataSource(s => { s.Read(r => r.Action("GetSupplier", "AutoComplete")).ServerFiltering(true); })
Controler
public JsonResult GetSupplier() {
var md = db.Regions.ToList();
List<RegionInfo> ls = new List<RegionInfo>();
foreach (var item in md) {
ls.Add(new RegionInfo{ RegionDescription = item.RegionDescription , RegionID = item.RegionID});
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var json = ser.Serialize(ls);
return Json(JArray.Parse(json), JsonRequestBehavior.AllowGet);
}
Image error
Please give me advise. Thanks
Related
I have a custom button that I have the below JavaScript attached to that opens an entity form and I am trying to pass viewName to it.
function sendContextToQC(selectedControl) {
var entityFormOptions = {};
entityFormOptions["entityName"] = "new_qrecipemasteritem";
entityFormOptions["useQuickCreateForm"] = true;
var currentView = selectedControl.getViewSelector().getCurrentView().name;
var formParameters = {};
formParameters["viewName"] = currentView
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
console.log(success);
},
function (error) {
console.log(error);
});
}
The form opens fine and I have the "Pass Execution Context as first parameter" checked, but I don't know how to access the formparameters object. Is it part of the executionContext? I even tried adding another parameter (formParameters), but that didn't work either.
2/14/23
You can access the form parameters from within the form by using the getFormContext() method. Here's an updated version of your code that shows how to access the formParameters object from within the form:
function sendContextToQC(selectedControl) {
var entityFormOptions = {};
entityFormOptions["entityName"] = "new_qrecipemasteritem";
entityFormOptions["useQuickCreateForm"] = true;
var currentView = selectedControl.getViewSelector().getCurrentView().name;
var formParameters = {};
formParameters["viewName"] = currentView;
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
var formContext = success.getFormContext();
var viewName = formContext.getAttribute("viewName").getValue();
console.log("View Name: " + viewName);
},
function (error) {
console.log(error);
});
}
In the success callback of the openForm method, you use getFormContext() to get a reference to the form context, and then use that reference to access the viewName attribute. You can then use the getValue() method on the attribute to retrieve its value.
In function Xrm.Navigation.openForm argument formParameters is an object holding field values. The function passes these values to the fields that are (should be) on the form opened by it.
It is possible to pass custom query string parameters to the form. These parameters can be retrieved accessing the window.location object.
See openForm - MS Learn and Configure a form to accept custom querystring parameters - MS Learn.
The (classic) Form Properties dialog has a Parameters tab where custom parameters can be declared. Custom parameters that have not been configured here can only be passed in a plain url by adding an extraqs parameter.
I figured it out. To send parameter:
function sendContextToQC(selectedControl) {
var entityFormOptions = {};
entityFormOptions["entityName"] = "new_qrecipemasteritem";
entityFormOptions["useQuickCreateForm"] = true;
var currentView = selectedControl.getViewSelector().getCurrentView().name;
var formParameters = {};
if (currentView.includes("Master") == true) {
formParameters["isMasterView"] = 1;
}
else {
formParameters["isMasterView"] = 0;
}
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
console.log(success);
},
function (error) {
console.log(error);
});
}
Then to pick it up onload:
this.hideUsedIn = function(executionContext) {
let formContext = executionContext.getFormContext();
let usedInAttribute = formContext.getAttribute("new_usedin");
let usedInControl = formContext.getControl("new_usedin");
let buttonData = {};
buttonData = Xrm.Utility.getPageContext().input.data;
let isMasterItem = buttonData.isMasterView;
if (isMasterItem === 1){
usedInAttribute.setRequiredLevel("none");
usedInControl.setVisible(false);
}
}
Hi Have This Code, I Want This Function To Return A List Of CLS_EL_ARCHIVE Objects But I Get This Error :
'CLS_EL_ARCHIVE' does not contain a constructor that takes 0 argument
public override IEnumerable<CLS_EL_ARCHIVE> GetAll()
{
DataTable DT = DAC.SelectData("SP_GET_ALL", new SqlParameter[] { new SqlParameter("#Table", "ARCHIVE") });
List<CLS_EL_ARCHIVE> ArchiveList = new List<CLS_EL_ARCHIVE>();
ArchiveList = DT.AsEnumerable().Select(Row => new CLS_EL_ARCHIVE
{
ArchiveId = Row.Field<int>("ArchiveId"),
Label = Row.Field<string>("Label"),
Date = Row.Field<DateTime>("Date"),
Note = Row.Field<string>("Note")
});
return ArchiveList;
}
This is working for me :) waiting for more answers
DataTable DT = DAC.SelectData("SP_GET_ALL", new SqlParameter[] { new SqlParameter("#Table", "ARCHIVE") });
List<CLS_EL_ARCHIVE> ArchiveList = new List<CLS_EL_ARCHIVE>();
ArchiveList = DT.AsEnumerable().Select(Row => new CLS_EL_ARCHIVE(Row.Field<int>("ArchiveId"), Row.Field<string>("Label"),
Row.Field<DateTime>("Date"), Row.Field<string>("Note"))).ToList();
I Have the following test:
[Test]
public void Add_New_Group_Should_Return_StatusCode_Created_And_A_Header_Location_To_The_New_Group()
{
var newGroup = new GroupData { ID = 1, UserID = 1, Name = "Group 1", Description = "Description 1" };
var fakeGroupDAL = A.Fake<IGroupDAL>();
var contactGroupsController = new ContactGroupsController(fakeGroupDAL);
SetupControllerForTests(contactGroupsController, HttpMethod.Post);
var response = contactGroupsController.AddGroup(new ContactGroupApiRequest(), newGroup);
Assert.IsTrue(response.StatusCode == HttpStatusCode.Created, "Should have returned HttpStatusCode.Created");
}
Which calls the following configuration method:
private static void SetupControllerForTests(ApiController controller, HttpMethod httpMethod)
{
var config = new HttpConfiguration();
var request = new HttpRequestMessage(httpMethod, "http://localhost/contactgroups");
var route = config.Routes.MapHttpRoute("ContactGroupsApi", "{controller}/{action}/{request}", new { request = RouteParameter.Optional });
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "contactgroups" } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
}
I'm trying to test the following action method:
[HttpPost]
public HttpResponseMessage AddGroup([FromUri]ApiRequest req, [FromBody] GroupData contactGroup)
{
if(ModelState.IsValid && contactGroup !=null)
{
_groupDal.AddGroup(contactGroup);
contactGroup.Name = HttpUtility.HtmlEncode(String.Format("{0} - {1}", contactGroup.Name, contactGroup.Description));
var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(contactGroup.Name) };
var uriString = Url.Link("ContactGroupsApi", new { controller = "contactgroups", action = "Group", UserId = contactGroup.UserID, GroupId = contactGroup.ID});
response.Headers.Location = new Uri(uriString);
return response;
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
The action method works perfectly well when called normally, but fails under test because the call to Url.Link returns null.
var uriString = Url.Link("ContactGroupsApi", new { controller = "contactgroups", action = "Group", UserId = contactGroup.UserID, GroupId = contactGroup.ID});
All this code is based very closely on the following article: Unit test ASP.NET Web Api
I suspect that when running under test there is insufficient route table info. Any idea what I'm doing wrong?
I fixed my tests by adding the HttpRouteData to the HttpRouteDataKey property of the controller's HttpRequestMessage. Like this:
controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
Hi all i have ajax where i have some data And a controller action method ...i need to send the data to the controller action method ...when i am doing this it has null values in my controller method ,can any one correct me where am i doing worng...
<script type="text/javascript">
$(document).ready(function () {
$("#butValidateForm").click(function () {
UpdateMethod();
})
});
function UpdateMethod() {
var s = document.getElementById("EmployeeID");
var selecteditem1 = s.options[s.selectedIndex].value;
var a = document.getElementById("FromStatusId");
var selecteditem6 = a.options[a.selectedIndex].value;
var data = '{"AssignTo":"' + selecteditem1 + '","Status":"' + selecteditem6 + '"}';
alert(data);
$.ajax({
type: "POST",
url: "/ViewBug/Update/",
enctype: 'multipart/form-data',
data: data,
success: function () {
}
});
}
</script>
my contoller action method
[HttpPost]
public ActionResult Update(BugModel model, FormCollection form, string selecteditem1, string selecteditem6)
{
if (Session["CaptureData"] == null)
{
}
else
{
model = (BugModel)Session["CaptureData"];
}
ViewBag.AssignTo = new SelectList(GetEmployee(), "EmployeeID", "EmployeeName");
ViewBag.Status = new SelectList(GetFromStatus(), "FromStatusId", "FromStatus");
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("sp_history", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.Parameters.Add("#Title", SqlDbType.VarChar).Value = model.Title;
cmd.Parameters.Add("#FixedById", SqlDbType.VarChar).Value = model.LoginName;
cmd.Parameters.Add("#AssignedId", SqlDbType.Int).Value = model.AssignTo;
cmd.Parameters.Add("#Resolution", SqlDbType.VarChar).Value = model.Resolution;
cmd.Parameters.Add("#FromStatus", SqlDbType.VarChar).Value =model.Status;
string fileName = string.Empty;
string StrFilePath = string.Empty;
foreach (BugAttachment objList in model.ListFile)
{
if (string.IsNullOrEmpty(StrFilePath))
{
fileName = objList.AttachmentName;
StrFilePath = objList.AttachmentUrl;
}
else
{
fileName = fileName + "," + objList.AttachmentName;
StrFilePath = StrFilePath + "," + objList.AttachmentUrl;
}
}
cmd.Parameters.Add("#AttachmentName", SqlDbType.VarChar).Value = fileName;
cmd.Parameters.Add("#BugAttachmentUrl", SqlDbType.VarChar).Value = StrFilePath;
cmd.Parameters.Add("#AttachedBy", SqlDbType.VarChar).Value = model.LoginName;
cmd.ExecuteNonQuery();
conn.Close();
}
return View("Edit");
}
Instead of
public ActionResult Update(BugModel model, FormCollection form, string selecteditem1, string selecteditem6)
give this a try:
public ActionResult Update(BugModel model, FormCollection form, string AssignTo, string Status)
You need to use the names of the property you have used in the object your sending back as you have named them AssignTo and Status. Hope this helps.
Edit:
Try sending the object like this:
var data ={};
data.AssignTo = selectedvalue1;
data.Status = selectedvalue6;
See if that makes any difference. If your still having issues can you inspect the request in firebug/developer tools?
Try this:
var data = { AssignTo: selecteditem1, Status: selecteditem6 };
also, as per Henry's answer, use the signature:
public ActionResult Update(BugModel model,
FormCollection form,
string AssignTo,
string Status)
tho, you should of course be able to get both the required values from the form[] collection, given that you are doing an HttpPost behind the scenes:
(i.e. var assignTo = form["AssignTo"]; etc).
[Edit] - out of curiousity, can I ask why you mix and match jquery syntax with more traditional javascript object syntax. one example being where you get the value of the EmployeeID option?? why not just use var selecteditem1 = $('#EmployeeID').val();.
I also notice the ViewBag object getting updated in your HttpPost action. Are you expecting to be able to use that on returning to the view -surely not (not in terms of the ajax request anyway). A quick explanation for my curiousity would be great. In my opinion, you are trying to do too much with this action (sure, keep it DRY - but) and I'm fearful that you'll end up getting into a corner with the number of different entry points you appear to be building up. I'd suggest a gentle rewind, just to keep things a little more focussed and each action having a single responsibility.
I ended up doing the following:
<script type="text/javascript">
$(document).ready(function () {
$("#butValidateForm").click(function () {
UpdateMethod();
})
});
function UpdateMethod() {
var s = document.getElementById("EmployeeID");
var selecteditem1 = s.options[s.selectedIndex].value;
var a = document.getElementById("FromStatusId");
var selecteditem6 = a.options[a.selectedIndex].value;
// var data = '{AssignTo:' + selecteditem1 + '}';
// alert(data);
var AssignTo;
var Title;
Title=$("#Title").val();
var FixedBy;
FixedBy = $("#LoginName").val();
var Resolution;
Resolution = $("#Resolution").val();
var Status;
Status = $("#FromStatusId").val();
$.ajax({
type: "POST",
url: "/ViewBug/Update/",
enctype: 'multipart/form-data',
data: {AssignTo:selecteditem1,Title:Title,FixedBy:FixedBy,Resolution:Resolution,Status:Status},
success: function () {
}
});
}
</script>
I wonder if anybody can help me here. I apologise for sounding like a thicko but I'm new to MVC3 and I'm trying to pass 2 values from a view to an action method but it just isn't playing fair!
HTML:
#Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager",
new { htmlTokenId = item.Id }, new { htmlDataTemplateId = 1 })
ACTION METHOD:
public ActionResult AssignTokenToDataTemplate(int htmlTokenId, int htmlDataTemplateId)
{
// Do some database stuff here
return View("AssignAnExistingTokenToHtmlDataTemplate", new {templateId = htmlDataTemplateId});
}
I want to pass two integers into the AssignTokenToDataTemplate action method but I cannot get it to work?!
Can anybody see where I'm going wrong? :(
Try
#Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager",
new { htmlTokenId = item.Id , htmlDataTemplateId = 1 })
However you might want to consider using a model (a type of your own) to pass them together as one.
You could pass both values using the routeValues parameter:
#Html.ActionLink(
"ASSIGN", // linkText
"AssignTokenToDataTemplate", // actionName
"HostHtmlTokenManager", // controllerName
new { // routeValues
htmlTokenId = item.Id,
htmlDataTemplateId = 1
},
null // htmlAttributes
)
You have to include both parameters in the anonymous class:
#Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager",
null, new { htmlDataTemplateId = 1, htmlTokenId = item.Id })
Try;
#Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager",
new { htmlTokenId = item.Id, htmlDataTemplateId = 1 })
Matt