Ive got a dropdown on one of my views. This dropdown only has for entries. Basically i need to know how to call an action when the dropdown value is changed?
My situation is: Im making a simple inbox page. The dropdown has the filter options: View All, View Invites, View Replies etc..
When the user selects a filter option from the dropdown I want to call to an action to return the new view with the filtered data.
Any ideas? Im guessing it is somehow going to be a script attached to the OnChange of the dropdown, but i wouldnt have a clue what the syntax is or how call MVC action from the script.
Thanks in advance
You need to use javascript for this. Here's an example. Suppose you have the following view model:
public class MyViewModel
{
public IEnumerable<SelectListItem> Values { get; set; }
}
which you would populate in your controller:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Values = new[]
{
new Item { Value = "1", Text = "Item 1" },
new Item { Value = "2", Text = "Item 2" },
new Item { Value = "3", Text = "Item 3" }
}
};
return View(model);
}
}
And then the view which is strongly typed to this model:
<%: Html.DropDownListFor(x => x.SelectedValue,
new SelectList(Model.Values, "Value", "Text"),
new { id = "items" }
)%>
The last part is to register for the change event (using jquery in this example):
$(function () {
// Register for the change event of the drop down
$('#items').change(function () {
// When the value changes, get send an AJAX request to the
// Filter action passing the selected value and update the
// contents of some result div with the partial html returned
// by the controller action
$('#result').load('<%: Url.Action("filter") %>',
{ selectedValue: $(this).val() }
);
});
});
Related
I am attempting to build a simple lightning component that will display field values from the object that it is referencing on the page. I have applied the tutorial but cannot get the field values to display on the page.
It is not clear to me how to reference the id of the object on the page and/or whether it is necessary for the apex query or if the field value can be rendered without it.
Position__c is the reference object API with some fields:
This is my component:
<aura:component implements="flexipage:availableForAllPageTypes" controller="positionController" access="global">
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="recordId" type="Id" />
<aura:attribute name="position" type="Position__c"/>
{!v.position.Job_Posting_One_liner__c} //I really just need to print this field value
</aura:component>
Controller:
({
doInit : function(component, event, helper) {
var recordId = component.get("v.recordId");
var action = component.get("c.getPositionDetails");
action.setParams({
"PosId": recordId
});
action.setCallback(this, function(response){
var state = response.getState();
if (component.isValid() && state === "SUCCESS") {
var position = response.getReturnValue();
component.set("v.position", position);
}
});
$A.enqueueAction(action);
}
Apex:
public class positionController {
#AuraEnabled
public static Position__c getPositionDetails(Id PosId) {
Position__c positions =
[SELECT Id, Job_Posting_One_liner__c FROM Position__c Where Id= :PosId limit 1 ];
return positions;
}
}
In js controller try remove quotes from this line:
action.setParams({
"PosId": recordId
});
so that it reads like this:
action.setParams({ PosId: recordId });
My requirement is to build lightning datatable dynamically.
I can able to dynamically create and view lightning data table. But as soon as I am adding "onrowselection":component.getReference("c.getSelectedRecord") line, datatable is not rendering. So adding this line is causing the issue, but I need to hookup onrowselection event.
What is the proper way to add onrowselection event dynamically to my dynamically created datatable?
Error Reproduce: I have prepared demo code below.
Component: demoDynamicDataTable.cmp
<aura:component controller="demoDynamicDataTableController">
<aura:attribute name="returnList" type="Contact[]" access="public"/>
<aura:attribute name="returnColumns" type="List" access="public"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<lightning:button label="Create Data Table" onclick="{!c.createDT}" variant="brand"/>
<div aura:id="newDtPlaceholder">
{!v.body}
</div>
</aura:component>
JS Controller: demoDynamicDataTableController.js
({
doInit : function(component,event,helper) {
console.log("doinit");
//Column data for the table
var columns = [
{
label:'Customer Name',
fieldName:'Name',
type:'text'
},
{
label:'Phone#',
fieldName:'Phone',
type:'text'
}
];
//pass the column information
component.set("v.returnColumns",columns);
//recriving data from server
helper.fetchData(component);
},
createDT : function(component, event, helper) {
//Creating dynamic Lightning datatable
var targetCmp=component.find("newDtPlaceholder");
targetCmp.set("v.body",[]); //destroying existing one
$A.createComponent(
"lightning:datatable",
{
"data":component.get("v.returnList"),
"columns":component.get("v.returnColumns"),
"keyField":"Id",
"maxRowSelection":"1",
"onrowselection":component.getReference("c.getSelectedRecord") //adding this line is causing the issue. But I need to hookup onrowselection event
},
function(tbl,state,message)
{
console.log(state +" - " +message);
var body=targetCmp.get("v.body");
body.push(tbl);
targetCmp.set("v.body",body);
}
);
},
getSelectedRecord: function(component, event, helper){
var selectedRows = event.getParam('selectedRows');
console.log(JSON.stringify(selectedRows[0]));
}
})
Helper: demoDynamicDataTableHelper.js
({
fetchData : function(cmp) {
var action = cmp.get("c.getContact");
action.setCallback(this,function(resp){
var state = resp.getState();
if(state === 'SUCCESS'){
var records = resp.getReturnValue();
//console.log(JSON.stringify(records));
//pass the records to be displayed
cmp.set("v.returnList",records);
}
});
$A.enqueueAction(action);
}
})
Apex Controller: demoDynamicDataTableController.apxc
public class demoDynamicDataTableController {
#AuraEnabled
public static List<Contact> getContact(){
return [Select Id,Name,Phone from Contact];
}
}
App: demoDynamicDataTableApp.app
<aura:application extends="force:slds">
<c:demoDynamicDataTable/>
</aura:application>
Trying to create a new form group inside of the existing form group in Angular 2. I define the main form in one of the component with the empty formGroup "type". I pass that formGroup "type" to another component. In that component I want to create a new formGroup with name "time", but it doesn't work. I didn't find any method in the FormGroup class for creating a new group. There is just methods for Controls for adding them to the FormGroup.
addControl method works but the next one not.
this.typeForm.addControl("gender", new FormControl('', Validators.required));
this.typeForm['time'] = this.fb.group({});
The FormBuilder should create something like:
{
"name": "",
"type": {
"gender": "",
"time": {
}
}
}
Any idea how can I do that?
I think you can try to do something like this:
ngOnInit() {
this.form = this.fb.group({
name: [''],
type: this.typeOptions()
});
}
typeOptions(): FormGroup {
return this.someService.getTypes().subscribe(
res => {
this.options = res.body;
let obj: any = {};
for (let option of options) {
let control: FormControl = new FormControl(option.value || '');
obj[option.title] = control;
}
return new FormGroup(obj);
}
);
}
I've defined the following route:
routes.MapRoute(
null,
"foo/{id}/{title}",
new { controller = "Boo", action = "Details" }
);
When I call this method:
Url.Action("Details", "Boo", new { id = article.Id, title = article.Title })
I get the following URL:
http://localhost:57553/foo/1/Some%20text%20Š
I would like to create a new route that will lowercase all characters and replace some of them.
e.g.
http://localhost:57553/foo/1/some-text-s
Rules:
Uppercase -> lowercase
' ' -> '-'
'Š' -> 's'
etc.
Any help would be greatly appreciated!
Seems like a perfect candidate for a custom route:
public class MyRoute : Route
{
public MyRoute(string url, object defaultValues)
: base(url, new RouteValueDictionary(defaultValues), new MvcRouteHandler())
{
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
values = new RouteValueDictionary(values);
var title = values["title"] as string;
if (!string.IsNullOrEmpty(title))
{
values["title"] = SEOify(title);
}
return base.GetVirtualPath(requestContext, values);
}
private string SEOify(string title)
{
throw new NotImplementedException();
}
}
which will be registered like this:
routes.Add(
"myRoute",
new MyRoute(
"foo/{id}/{title}",
new { controller = "Boo", action = "Details" }
)
);
Now all you have to do is to implement your SEO requirements in the SEOify function that I left. By the way you could get some inspiration from the way StackOverflow does it for the question titles.
Currently I have a Controller named StoreController. There are three Categories : books, movies, and games. How can i make sure that the url's
http://mywebsite.com/store/books,
http://mywebsite.com/store/movies
http://mywebsite.com/store/games
match a single action method. Right now, I am having three separate action methods books(); movies(); games(); doing the same thing, i.e listing the products in them
Did you try like this?
routes.MapRoute(
"Default", // Route name
"{controller}/{id}", // URL with parameters
new { controller = "Store", action = "Index", id = UrlParameter.Optional } // Parameter defaults
, null }
)
and you make Controller like
public ActionResult Index(string id)
{
if(id == "books"){
}
else if(id == "movies"){
}
else{// this is null case
}
return Content("hello");// test
}