I have this helper code
#helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
#{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
#if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span id="Category">
#i.CategoryName
<b></b>
</span>
#if (submenu > 0)
{
<ul>
#Treeview.GetTreeView(siteMenu, i.ID)
#* Recursive Call for Populate Sub items here*#
</ul>
}
</li>
}
}
and i want to pass the id to a Action method of a controller.
How to pass the id from view to a action method in controller.
$('#Category').click(function () {
url = '#Url.Action("Index", "TestDetails");
$.ajax({
url: url,
type: 'POST',
success: function (returnData) {
},
error: {
}
});
});
How can i get the id in the second snippet of code.
Using that id i have to fetch some details using a action method in my controller.
Action Method
public ActionResult Index(int id)
{
TestDetail detail = new TestDetail();
detail = db.TestDetails.Single(a => a.ID == id);
return View(detail);
}
simply pass "this" to your onclick function
<span class="Category">
#i.CategoryName
<b></b>
</span>
Javascript: (Edited)
<script type="text/javascript">
function CategoryClick(clicked_id)
{
alert(clicked_id);
url = '#Url.Action("TestDetails", "Index")'; //Url.Action(actionName, ControllerName)
$.ajax({
url: url,
data: {id: clicked_id}, //json format
success: function (returnData) {
},
error: {
}
});
}
</script>
Edit your helper as following:
#helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
#{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
#if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span >
<a class="Category" href="#" id="#i.ID">#i.CategoryName</a>
<b></b>
</span>
#if (submenu > 0)
{
<ul>
#Treeview.GetTreeView(siteMenu, i.ID)
#* Recursive Call for Populate Sub items here*#
</ul>
}
</li>
}
}
and the ajax call:
$('.Category').click(function () {
url = '#Url.Action("Index", "TestDetails")';
$.ajax({
url: url,
type: 'POST',
data: "{'id': " + $(this).attr("id") + "}",
success: function (returnData) {
},
error: {
}
});
});
Related
I am trying to pass parameter from view to controller,
This is my View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#foreach (var pricedetails in ViewBag.PriceTotal)
{
<div style="text-align:center; clear:both ">
<h5 class="product-title">#pricedetails.Title</h5>
</div>
<div class="product-desciption" style="height:40px">#pricedetails.Descriptions</div>
<p class="product-desciption product-old-price"> #pricedetails.PricePoints</p>
<div class="product-meta">
<ul class="product-price-list">
<li>
<span class="product-price">#pricedetails.PricePoints</span>
</li>
<li>
<span class="product-save">Get This Free</span>
</li>
</ul>
<ul class="product-actions-list">
<input type="submit" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />
</ul>
</div>
}
}
my action method:
On submit it reaches the Action Method, but I am not able to get the PriceId for each Price
[HttpPost]
public ActionResult Index(int id=0) // here PriceId is not passed on submit
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Content("<script language='javascript' type='text/javascript'>alert('You are not elgible');</script>");
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('You are elgible');</script>");
}
return View("Index");
}
Url Routing:
routes.MapRoute(
name: "homeas",
url: "Index/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
May I know what wrong I am doing ?
Please use the following in your cshtml page
#foreach (var item in Model)
{
#Html.ActionLink(item.PriceDetails, "GetGift", new { priceID = item.priceID }, new { #class = "lnkGetGift" })
}
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a.lnkGetGift").on("click", function (event) {
event.preventDefault();
$.get($(this).attr("href"), function (isEligible) {
if (isEligible) {
alert('eligible messsage');
}
else
{
alert('not eligible messsage');
}
})
});
});
</script>
and in controller
[HttpGet]
public JsonResult GetGift(int priceID)
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
Please change your parameters according to the method param and price entity
Hope this helps.
I suggest you get rid of the Html.BeginForm(). Just leave the for...loop and define your "Get Gift" button like this:
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(pricedetails.PriceId))'" />
Then, at the bottom of the view file where the Get Gift button is located, define some JavaScript:
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("Index", "Home")',
data: { priceId: priceId },
contentType : "json",
success:function(data){
// Do whatever in the success.
},
error:function(){
// Do whatever in the error.
}
});
</script>
By using an ajax call to get the gift data, you don't have to submit anything. This makes things a lot easier in your case. Pressing the Get Gift button simply makes an ajax call.
I don't have time to try this out myself, but hopefully the above example should get you up and running.
EDIT:
I've managed to sneak in some time to come up with an example.
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var items = new List<int>();
items.Add(1);
items.Add(2);
items.Add(3);
return View(items);
}
public ActionResult GetGift(int priceId)
{
return RedirectToAction("Index"); // You'll be returning something else.
}
}
View
#model List<int>
#foreach (var price in Model)
{
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(price))" />
}
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("GetGift", "Home")',
data: { priceId: priceId },
contentType: "json",
success: function(data) {
// Do whatever in the success.
},
error: function() {
// Do whatever in the error.
}
});
}
</script>
Hope this helps you.
I think you should correct here
<input type="button" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />
How i can add active class to menu with angular with this case
html code
<div class="categories" ng-controller="CategoryController">
<ul class="menu">
<li ng-repeat="category in categories">
<a ng-click="sendCategory(category)">{{category.name}}</a>
</li>
</ul>
</div>
js code
myApp.factory('Categories', ['$http',
function ($http) {
return {
get: function (callback) {
$http.get('data/categories.json').success(function (data) {
callback(data);
})
}
}
}
]);
use this syntax:
<ul class="menu" ng-class="{classname: variableFromScope}">
Set this variable to true or false (to activate or disactivate your classname class) in your controller where it needed:
$scope.variableFromScope = true;
here is solution
html code
<ul class="menu">
<li ng-repeat="category in categories"><a ng-click="sendCategory(category)" ng-class="{ active: activePath=='/{{category.name}}' }">{{category.name}}</a>
</li>
</ul>
js code
`
myApp.controller('CategoryController', function ($scope, $route, $location, $http, Categories){
Categories.get(function (response) {
$scope.categories = response;
});
$scope.sendCategory = function (category) {
$location.path(category.name);
};
$scope.activePath = null;
$scope.$on('$routeChangeSuccess', function () {
$scope.activePath = $location.path();
console.log($location.path());
});
})`
I have li tags that includes links to different pages. Now i am trying to create a searcj by clicking on specific li tag. I want when user clicks on this li named 'Field Workers', a sub li appears that includes names of all field workers that are in the database. Ajax code is used to diaplay the field workers. I am getting data in the ajax cide but somehow it is not getting displayed. Can anyone help me with this?
Ajax code:
<script>
var ajaxOptions = {
type: "POST", url: null, success: null, async: true,
data: "", dataType: "json", contentType: "application/json; charset=utf-8"
}
$(function () {
BindFW();
})
function BindFW() {
ajaxOptions.data = "";
ajaxOptions.url = "WebForm1.aspx/BindFieldWorkers"
ajaxOptions.success = function (result) {
if (result.d != null && result.d != "") {
//$("#templateFW").tmpl(result.d).appendTo("#ulFW");
$.each(result.d, function () {
$('#ulFW').append();
});
}
}
$.ajax(ajaxOptions);
}
</script>
<ul>
<li class="has-sub">
<a href="javascript:;">
<i class="icon-search"></i>
<span class="title">Field Worker Name</span>
<span class="arrow "></span>
</a>
<ul id="ulFW" class="sub">
</ul>
</li>
</ul>
use from this script:
$(document).ready(function () {
BindFW(10);
});
function BindFW(StateId) {
var data = {
StateId: StateId
};
$.ajax({
type: 'POST',
url: './WebForm1.aspx/BindFieldWorkers',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(data),
success: function (data) {
if (!data.d['Result']) {
alert('no records found!');
return;
}
var records = data.d['Records'];
for (var i = 0; i < records.length; i++) {
$('#ulFW').append(function () {
return $('<li>').text(records[i].Text).attr('data-id', records[i].ID)
});
}
},
error: function (data) {
alert('failed to connect to server!');
}
});
}
and this in your code behind:
[System.Web.Services.WebMethod]
public static object BindFieldWorkers(int StateId)
{
try
{
List<object> result = new List<object>();
for (int i = 0; i < 10; i++)
{
result.Add(new
{
ID = i,
Text = "Text " + i
});
}
return new { Result = true, Records = result };
}
catch (Exception ex)
{
return new { Result = false, Message = ex.Message };
}
}
<ul>
#foreach (var item in Model.Users.Where(s => s.DepartmentId == 3))
{
<li>
#Ajax.ActionLink(item.UserName, "Index", new { item.Id }, new AjaxOptions() { HttpMethod = "Get" });
</li>
}
</ul>
How can ı get item.Id if i onclick item.username with javascript ?
I thought give to attribute to "li onclick".but i dont know there is better solution here or not ?
You could use a standard link and data-* attribute:
<ul>
#foreach (var item in Model.Users.Where(s => s.DepartmentId == 3))
{
<li>
#Html.ActionLink(
item.UserName,
"Index",
new { id = item.Id },
new { #class = "myLink", data_id = item.Id }
)
</li>
}
</ul>
and then in a separate javascript file:
$(function() {
$('.myLink').click(function() {
// get the id:
var id = $(this).data('id');
alert(id);
// now you can send the AJAX request
$.get(this.href);
// cancel the default action of the link
return false;
});
});
i have a PartialView in my MVC Appliction, which returns my View if there are any Errors in the ModelState. In the _Layout site are many javascript ( jQuery, JQuery.validate, ... ) references which i use in the partai view.
Here the Code:
Javascript submit:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
if ($('form').valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (!result.Success) {
$('#formcontent').html(result); // Show PartailView with Validationmessages
}
else {
}
}
});
}
});
});
Parent Site:
<div id="formcontent" class="tc-form">
#{ Html.RenderPartial( "_ConfigurationPartial", Model ); }
</div>
Partial View:
#model SettingsViewModel
#{ Layout = null; }
#using( Html.BeginForm() )
{
#Html.ValidationSummary( false, SystemStrings.ValidationSummaryMessage )
<ol class="last">
<li class="row">
#Html.LabelFor( m => m.PasswordMinimumLength )
#Html.EditorFor( m => m.PasswordMinimumLength )
#Html.ValidationMessageFor( m => m.PasswordMinimumLength, "*" )
</li>
<li class="row">
#Html.LabelFor( m => m.PasswordNeverExpires )
#Html.EditorFor( m => m.PasswordNeverExpires )
#Html.ValidationMessageFor( m => m.PasswordNeverExpires, "*" )
</li>
<li class="row">
#Html.LabelFor( m => m.PasswordExpirationValue )
#Html.EditorFor( m => m.PasswordExpirationValue )
#Html.ValidationMessageFor( m => m.PasswordExpirationValue, "*" )
#Html.EditorFor( m => m.PasswordExpirationUnit )
#Html.ValidationMessageFor( m => m.PasswordExpirationUnit, "*" )
</li>
</ol>
<div class="tc-form-button">
<input type="submit" value="Save" title="Save" class="t-button t-state-default" />
#Html.ActionLink( "Cancel", "Configuration", "System", null, new { #class = "t-button" } )
</div>
}
<script type="text/javascript">
jQuery(document).ready(function () {
$('#PasswordNeverExpires').change(function () {
setState($(this).is(':checked'));
});
});
function setState(isDisabled) {
if (isDisabled) {
// ...
}
else {
// ...
}
}
Controller:
[HttpPost]
public ActionResult Configuration( SettingsViewModel model )
{
if( !ModelState.IsValid )
{
this.PopulateViewData();
return PartialView( "_ConfigurationPartial", model );
}
else
{
// ... do save
return Json( new { Success = true }, JsonRequestBehavior.AllowGet );
}
}
If the partialView is load via ajax all my Javascript are broken. There is no second ajax submit, it is a normal post. So the partialvew is rendered without any layout informations. It seems that all the javascript references are not found. Is there any way to refresh the DOM or something else? Must i have all the javascript in the PartailView? What is the correct way for this?
Regards
This code is outside of Partial View:
<script type="text/javascript">
jQuery(document).ready(function () {
var oldvalue=$('#PasswordNeverExpires').val();
$('#PasswordNeverExpires').change(function(){
oldvalue=$(this).val();
})
});
</script>
Then I change your code in PartialView a little:
jQuery(document).ready(function () {
if($('#PasswordNeverExpires').val()!=oldvalue){
//your scripts put here.
}
});
The above code was not tested but It should work.
Your problem is that you bind the submit event to the form when the page is loaded for the first time. When you reload the form through ajax you need to rebind the submit event to your new form.
You can also live bind the event, which you do only once
$("form").live("submit", function(e) {
e.preventDefault();
if ($('form').valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
if (!result.Success) {
$('#formcontent').html(result); // Show PartailView with Validationmessages
}
else {}
}
});
}
});
read more here