I edited my codes
.factory('ProductsService',['$ionicSideMenuDelegate', '$http', 'ApiEndpoint', '$ionicTabsDelegate', '$ionicSlideBoxDelegate', '$stateParams', 'AuthService', function($ionicSideMenuDelegate, $http, ApiEndpoint, $ionicTabsDelegate, $ionicSlideBoxDelegate, $stateParams, AuthService){
var products = [];
var prod = [];
return {
GetProducts: function(){
return $http.get(ApiEndpoint.url + '/products', {}).then(function(response){
products = response.data.products;
return response;
});
},
GetProduct: function(productId){
angular.forEach(products, function(product, key){
$scope.prod = {}; //ERROR: $scope is not defined
if(product.id == productId){
prod = product;
return product;
}
})
return prod;
}
}
}])
..after I click the item that error appears..And the page doesnt show the details must shown..
I am not sure if I got your question.
Usally every View has its own Controller. So in your case one controller for the menu.html and for the productpage. Of course you can also use the same controller for both views.
If you want to use one controller for both views the controller can provide the data for both views.
If you want a controller for each view you have to share to data between the controllers. For sharing data between different controllers you can find a lot of help:
- Stackoverflow share data between controllers
- Thinkster using services to share data between controllers
In both solutions you had to call your api in this services. For that you should understand the angularjs concept of $q and promises:
Angularjs Documentation of $q
If could specifiy which data you want to call from which page to another, I can improve this answer.
EDIT:
Based on your comment I can add the following suggestion. In your products.html you want to display the details of a choosen product. Thats roughly said a master-detail-pattern. You can take a look at this: Master-Detail-Pattern.
You will have to change your state-config and add a state for the product-details. Something like that (you will have to change the code):
.state('productDetails', {
url: "/product/:id",
templateUrl: 'templates/product.html',
controller: 'yourCtrl'
});
In your controller you can get the given :id over the state-params:
var productId= $stateParams.id;
To achive that it works you also have to edit your menu.html. For every product you need a link which looks like:
{{product.name}}
This has to be wrapped in your ng-repeat. But that is all discribed on the given page.
Of course there are also other possibilities to do what you want.
Related
I want to make simple application using laravel5.2 in which there will come sign in form on base url when i log in to the application there need to give a different view i.e. Client dashboard at same url. How can i do that Please help me. Thanks In Advance !
You could do something like this for root / URL:
Route::get('/', function(){
if (!Auth::check()) {
return View::make('login'); // login view if not authenticated
// or call controller for login
}
else{
return View::make('dashboard'); // dashboard view if authenticated
// or call controller for dashboard
}
});
This is very simple. You have to just make a function in WelcomeController or in other controller. And do check if user is already login or not and redirect to proper view page accordingly.
For example :
In your routes.php file write route like this
$router->get('/',array(
'as' => 'home',
'uses' => 'WelcomeController#welcome'
));
And in your controller ,in case of this example : WelcomeController make a function named welcome and do some auth check like this
public function welcome()
{
if(Auth::check()){
//get some data for user dashboard
return view('dashboard');
}
return view('login');
}
PS: for good practice, use dependency injection. In this case inject Guard
class instead of using Auth facade.
(Contrived) example collection urls:
VERB /leagues
VERB /leagues/{leagueId}/teams
VERB /leagues/{leagueId}/teams/{teamId}/players
The goal is to configure my associations and proxies to automatically target these urls.
Currently, I have a model for each of League, Team, and Player, with a hasMany association chain in the direction of
(League) ---hasMany--> (Team) ---hasMany--> (Player)
with the the Id's of the owning model used as the foreign key in the associated model.
(I.e. each Team has a leagueId which equals the id of it's owning League, and each Player has a TeamId which equals the id of it's owning Team)
One attempt at solving this can be found here. However, it didn't work for me. My initial attempt was overriding the buildUrl method of the proxies as:
buildUrl: function(request) {
var url = this.getUrl(request),
ownerId = request.operation.filters[0].value;
url = url.replace('{}', ownerId);
request.url = url;
return Ext.data.proxy.Rest.superclass.buildUrl
.apply(this, arguments);
},
Which works perfectly for a url resource depth of 1 (VERB /leagues/{leagueId}/teams). The problem is when I do something like:
League.load(1, {
callback: function(league) {
league.teams().load({
callback: function(teams) {
// all good so far
var someTeam = teams[0];
someTeam.players().load({
// problem here. someTeam.players() does not have a filter
// with leagueId as a value. Best you can do is
// GET/leagues/undefined/teams/42/players
});
}
});
}
});
What do I need to override in order to get all the information I need to build the url in the buildUrl methods? I don't want to manually add a filter each time - that sort of defeats the purpose and I might aswel set the proxy each time.
Thanks for your help
My current (working) solution I came up with was to modify the constructor of internal resources and manually add filters to the generated stores there. For example:
App.models.Team
constructor: function() {
this.callParent(arguments);
this.players().filters.add(new Ext.util.Filter({
property: 'leagueId',
value: this.raw.leagueId
}));
return this;
},
and that way all the filter property:value pairs are available in the buildUrl methods via request.operation.filters.
I'll accept this answer for now (since it works), but will accept another answer if a better one is suggested.
I'm still quite new to ASP.NET MVC and wonder how-to achieve the following:
On a normal view as part of my master page, I create a varying number of partial views with a loop, each representing an item the user should be able to vote for. After clicking the vote-button, the rating shall be submitted to the database and afterwards, the particular partial view which the user clicked shall be replaced by the same view, with some visual properties changed. What is the best practice to achieve this?
Here's how I started:
1. I defined the partial view with an if-sentence, distinguishing between the visual appearance, depending on a flag in the particular viewmodel. Hence, if the flag is positive, voting controls are displayed, if it's negative, they're not.
I assigned a Url.Action(..) to the voting buttons which trigger a controller method. In this method, the new rating is added to the database.
In the controller method, I return the PartialView with the updated ViewModel. UNFORTUNATELY, the whole view get's replaced, not only the partial view.
Any suggestions how-to solve this particular problem or how-to achieve the whole thing would be highly appreciated.
Thanks very much,
Chris
Trivial (but by all means correct and usable) solution to your problem is Ajax.BeginForm() helper for voting. This way you change your voting to ajax calls, and you can easily specify, that the result returned by this call (from your voting action, which will return partial view with only 1 changed item) will be used to replace old content (for example one particular div containing old item before voting).
Update - 11/30/2016
For example:
#using (Ajax.BeginForm("SomeAction", "SomeController", new { someRouteParam = Model.Foo }, new AjaxOptions { UpdateTargetId = "SomeHtmlElementId", HttpMethod = "Post" }))
ASP.NET MVC is a perfect framework for this kind of needs. What I would do if I were in your possition is to work with JQuery Ajax API.
Following blog post should give you a hint on what you can do with PartialViews, JQuery and Ajax calls to the server :
http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views
UPDATE
It has been asked to put a brief intro so here it is.
The following code is your action method :
[HttpPost]
public ActionResult toogleIsDone(int itemId) {
//Getting the item according to itemId param
var model = _entities.ToDoTBs.FirstOrDefault(x => x.ToDoItemID == itemId);
//toggling the IsDone property
model.IsDone = !model.IsDone;
//Making the change on the db and saving
ObjectStateEntry osmEntry = _entities.ObjectStateManager.GetObjectStateEntry(model);
osmEntry.ChangeState(EntityState.Modified);
_entities.SaveChanges();
var updatedModel = _entities.ToDoTBs;
//returning the new template as json result
return Json(new { data = this.RenderPartialViewToString("_ToDoDBListPartial", updatedModel) });
}
RenderPartialViewToString is an extension method for controller. You
need to use Nuget here to bring down a very small package called
TugberkUg.MVC which will have a Controller extension for us to convert
partial views to string inside the controller.
Then here is a brief info on how you can call it with JQuery :
var itemId = element.attr("data-tododb-itemid");
var d = "itemId=" + itemId;
var actionURL = '#Url.Action("toogleIsDone", "ToDo")';
$("#ajax-progress-dialog").dialog("open");
$.ajax({
type: "POST",
url: actionURL,
data: d,
success: function (r) {
$("#to-do-db-list-container").html(r.data);
},
complete: function () {
$("#ajax-progress-dialog").dialog("close");
$(".isDone").bind("click", function (event) {
toggleIsDone(event, $(this));
});
},
error: function (req, status, error) {
//do what you need to do here if an error occurs
$("#ajax-progress-dialog").dialog("close");
}
});
There needs to be some extra steps to be taken. So look at the blog post which has the complete walkthrough.
I have a top-level page called ReceiveItem. Within that page, I have a couple different FORMs - only one of which will be filled out and submitted (depending upon how that item is received). This all works quite well from the UI perspective. Here is the general page structure:
<ReceiveItem.aspx>
<ReceiveNewInventory.ascx>
<ReceiveOrderReturn.ascx>
<ReceiveFromLoan.ascx>
Except, I do not know how to properly display validation errors. Here is my controller for one of those forms:
public ActionResult ReceiveNewInventory(
int id,
int vendorId,
int quantity,
decimal cost) {
var db = new Data();
var item = db.ItemSet.First(i => i.Id == id);
var vendor = db.BusinessSet.First(i => i.Id == vendorId);
ValidateCost(cost);
ValidateQuantity(quantity);
if (ModelState.IsValid) {
item.AddNewInventory(vendor, quantity, cost);
TempData["Message"] = "Added " + quantity +
" inventory items to " + item.FullDisplayName;
return RedirectToAction("Index");
}
else {
TempData["Quantity"] = quantity;
TempData["VendorId"] = vendorId;
TempData["Cost"] = cost;
return RedirectToAction("ReceiveItem", new { id });
}
}
I would like to display the model errors that the two validation functions add using the simple Html.ValidationSummary function; but, those errors seem to get lost because I do the RedirectToAction. (My ReceiveNewInventory controller action does not have a view directly associated with it.)
With the one condition that I still want 1 page with multiple FORMs, what can I change about this design so that my validation messages show up on the ReceiveItem page?
You need to put the ModelState into TempData and extract it in your ReceiveItem action method. Alternatively, change the Redirect to a return View()
hth
Dan
Look at NerdDinner and see how they do it. Very neat and you can display a summary at the top of the page as well as text next to each item if you wish.
let me know if you have trouble and I'll post code.
Why do you redirect to ReceiveItem even if you have errors? When you display the validation message, don't you want the user to have the opportunity to fix their mistakes? If so, why not keep them on the RecevieNewInventory page again and return the view?
Hi im new to MVC and I've fished around with no luck on how to build MVC User Controls that have ViewData returned to them. I was hoping someone would post a step by step solution on how to approach this problem. If you could make your solution very detailed that would help out greatly.
Sorry for being so discrete with my question, I would just like to clarify that what Im ultimatly trying to do is pass an id to a controller actionresult method and wanting to render it to a user control directly from the controller itself. Im unsure on how to begin with this approach and wondering if this is even possible. It will essentially in my mind look like this
public ActionResult RTest(int id){
RTestDataContext db = new RTestDataContext();
var table = db.GetTable<tRTest>();
var record = table.SingleOrDefault(m=> m.id = id);
return View("RTest", record);
}
and in my User Control I would like to render the objects of that record and thats my issue.
If I understand your question, you are trying to pass ViewData into the user control. A user control is essentially a partial view, so you would do this:
<% Html.RenderPartial("someUserControl.ascx", viewData); %>
Now in your usercontrol, ViewData will be whatever you passed in...
OK here it goes --
We use Json data
In the aspx page we have an ajax call that calls the controller. Look up the available option parameters for ajax calls.
url: This calls the function in the class.(obviously) Our class name is JobController, function name is updateJob and it takes no parameters. The url drops the controllerPortion from the classname. For example to call the updateJob function the url would be '/Job/UpdateJob/'.
var data = {x:1, y:2};
$.ajax({
data: data,
cache: false,
url: '/ClassName/functionName/parameter',
dataType: "json",
type: "post",
success: function(result) {
//do something
},
error: function(errorData) {
alert(errorData.responseText);
}
}
);
In the JobController Class:
public ActionResult UpdateJob(string id)
{
string x_Value_from_ajax = Request.Form["x"];
string y_Value_from_ajax = Request.Form["y"];
return Json(dataContextClass.UpdateJob(x_Value_from_ajax, y_Value_from_ajax));
}
We have a Global.asax.cs page that maps the ajax calls.
public class GlobalApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "EnterTime", action = "Index", id = "" } // Parameter defaults (EnterTime is our default controller class, index is our default function and it takes no parameters.)
);
}
}
I hope this gets you off to a good start.
Good luck
I am pretty sure view data is accessible inside user controls so long as you extend System.Web.Mvc.ViewUserControl and pass it in. I have a snippet of code:
<%Html.RenderPartial("~/UserControls/CategoryChooser.ascx", ViewData);%>
and from within my CategoryChooser ViewData is accessible.
Not sure if I understand your problem completely, but here's my answer to "How to add a User Control to your ASP.NET MVC Project".
In Visual Studio 2008, you can choose Add Item. In the categories at the left side, you can choose Visual C# > Web > MVC. There's an option MVC View User Control. Select it, choose a name, select the desired master page and you're good to go.