Hello I am trying to pass the parameter id to the a JsonResult. Currently the code below works if I hard code my id and when I do not pass a parameter through.
The code below is for the Events Calendar View
<script>
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: "prev,next,today",
center:'title',
right:''
// right: 'month'
},
defaultView: 'month',
editable:false,
allDaySlot: false,
selectable: true,
slotMinutes: 15,
firstDay:1,
events: 'GetEvents/'
});
});
</script>
<div id='calendar' style="width:90%">
</div>
JsonResult where the id is currently hard coded I would like to pass this value through when I click the button to load the page e.g. /EventsCalendar/2
public JsonResult GetEvents(string start , string end)
{
int id = 1;
var events = CustomEvents(start , end, id );
return Json(rows, JsonRequestBehavior.AllowGet);
}
Item 2 is the name of the button and Item 1 is the name
#Html.ActionLink(item.Item2, "ShowEvents", new { controller = "Leaves", id = item.Item1 }, new { #Class = "btn btn-primary" })
public ActionResult EventsCalendar()
{
return View();
}
Related
I want to set default value which will miss when click on the dropdown list.I would like to be unable to select "Please select" value. When I click on "Please select" value in materialId or depotId, "" null value send by ajax and I am getting error. How can I prevent this?
Create.cshtml
<div class="form-group">
#Html.LabelFor(model => model.materialId, "Material names", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("materialId", null, "Please select", htmlAttributes: new { #class = "form-control chosen" })
#Html.ValidationMessageFor(model => model.materialId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.depotId, "Product Outlet", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("depotId", null, "Please select", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.depotId, "", new { #class = "text-danger" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#depotId').change(function () { sendDataByAjax(); });
$('#materialId').change(function () { sendDataByAjax(); });
})
function sendDataByAjax() {
var materialId= $('#materialId option:selected').val();
var depotId= $('#depotId option:selected').val();
if (materialId == "" || depotId == "") {
// I can not write this
}
$.ajax({
type: "GET",
url: "#Url.Action("GetStock", "OutgoingProduct")",
data: {
'materialId': materialId,
'depotId': depotId
},
success: function (data) {
$("#stock").html(data);
}
});
}
</script>
}
I am getting error here when "" goes to my controller. Because it is not int.
OutgoingProductController.cs
public string GetStock(string materialId, string depotId)
{
int did = int.Parse(depotId);
int mid = int.Parse(materialId);
Since your dropdownlist selected values are passed as numeric values, you may use parseInt() function to try parsing numeric value from client-side and then check against NaN, if the value is numeric then trigger AJAX callback:
function sendDataByAjax() {
var materialId = parseInt($('#materialId option:selected').val());
var depotId = parseInt($('#depotId option:selected').val());
if (isNaN(materialId) || isNaN(depotId)) {
// do something, e.g. alert user
return false;
}
else {
$.ajax({
type: "GET",
url: "#Url.Action("GetStock", "OutgoingProduct")",
data: {
'materialId': materialId,
'depotId': depotId
},
success: function (data) {
$("#stock").html(data);
}
});
}
}
Then make sure that your action method contains int type for both parameters, hence no need to use int.Parse() which will throwing exception if parsed string has null value:
public ActionResult GetStock(int materialId, int depotId)
{
int did = depotId;
int mid = materialId;
// other stuff
}
Try returning false when materialId == "" || depotId == "" :
function sendDataByAjax() {
var materialId= $('#materialId option:selected').val();
var depotId= $('#depotId option:selected').val();
if (materialId == "" || depotId == "") {
return false;
}
$.ajax({
type: "GET",
url: "#Url.Action("GetStock", "OutgoingProduct")",
data: {
'materialId': materialId,
'depotId': depotId
},
success: function (data) {
$("#stock").html(data);
}
});
}
the way to solve this is not the way you're trying to do it. the way to do should be to use the validation system, available for MVC.
Change your get method to use a model, something like:
public class StockRequestModel
{
[Required]
public int materialId { get; set }
[Required]
public int depoId { get;set; }
}
Your controller method can then become something like:
public string GetStock([FromUri] StockRequestModel model)
{
if ( !ModelState.IsValid )
{
some code here
}
//at this point your model is valid and you have IDs so can proceed with your code
}
Normally, in MVC you would return the original View with the state in the result, so you can then trigger the front end validation. In your case, you seem to have a WebAPI controller in an MVC app, but you can still use front end validation.
There are other questions related to yours, such as Client side validation with Angularjs and Server side validation with Asp.net MVC
Normally I'd vote to close it as duplicate, but in this case, I think it's worthwhile pointing out the issue and solution.
Another place to go would be https://angularjs.org/ and then check the Form Validation section for pure front end validation. Of course you'd want to keep both front end and back end validations.
I have the following code to update my Cart items Quantity:
<div class="cart-col cart-col-qty" data-caption="Quantity">
<div id="item-count-#item.item_id">
#Html.TextBoxFor(model => model.CartItems[ix].Count,
new
{
#class = "test11 form-control",
#type = "text",
#min = "0"
})
<a href="#" class="RefreshQuantity tessss btn btn-danger btn-to-danger btn-sm btn-icon" data-id="#item.item_id"
txt-id="CartItems_#(ix)__Count"><i class="fa fa-2x">+</i></a>
</div>
I am using ajax to make a post request upon clicking the anchor element with this code:
$(".RefreshQuantity").click(function () {
// Get the id from the link
var recordToUpdate = $(this).attr("data-id");
var countToUpdate = $("#" + $(this).attr("txt-id")).val();
if (recordToUpdate != '') {
// Perform the ajax post
$.post("/ShoppingCart/UpdateCartCount", { "id": recordToUpdate, "cartCount": countToUpdate },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
}
location.reload();
});
}
});
I want to remove the click function on the anchor and use the input's onKeyUp event to make the ajax request with the cartItem id and the quantity without page refresh. How can I achieve this?
You can use this instead of .click
$("#YourElement").on('keyup', function (e) {
e.preventDefault(); //This will avoid post form
if (e.keyCode === 13) { //This evaluates enter key
//Your logic
}
});
I'm using this plugin, to make an autocomplete field inside a form to submit. It's all ok except when I submit the form, the field passed to the controller in the model is null. I don't know how to return the data I obtained.
That's my code html:
#Html.TextBoxFor(m => m.Team, new { #type = "text", id = "team", Name = "query", #class = "form-control", placeHolder = "Team (Ej -> Barcelona)", autocomplete = "off" })
JS code:
$('#team').typeahead({
ajax: "/Home/AutocompleteTeam",
responseText: [
$('#team').val()
]
});
C# code:
public ActionResult AutocompleteTeam(string query)
{
List<string> teams = new List<string>();
List<TeamServiceModel> teamsService = teamService.ListTeamsByQuery(query);
foreach (var team in teamsService)
{
if(team.Name.Equals("DEFAULT"))
{
continue;
}
else
{
teams.Add(team.Name);
}
}
return Json(teams, JsonRequestBehavior.AllowGet);
}
The service which is returning the list I'm filtering by the query is working.
Typeahead already filters result. You can make an ajax call to get all teams(return an array) and set 'local' field in typeahead with array values.
See more here http://www.bootply.com/ljIOxm3qDi
Here is my view in image
The code is working fine, but...
When i submit the form, it only sends the value of first dropdownlist (I checked on browser network received arguments), also when i view the page source it doesn't show the generated options that I generated using ajax function.
Here is my Code
Action that generate my first dropdownList
public ActionResult TwoDropDownList()
{
HotelContext H = new HotelContext();
ViewBag.DropDownListOne = new SelectList(H.Continent.ToList(), "Id", "Name");
return View();
}
Action that return json of second dropdownlist data
[HttpPost]
public JsonResult UpdateCountryDropDownList(int ContinentId)
{
HotelContext H = new HotelContext();
List<SelectListItem> CountryNames = new List<SelectListItem>();
List<Country> Co = H.Country.Where(x => x.ContinentId == ContinentId).ToList();
Co.ForEach(x =>
{
CountryNames.Add(new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
});
return Json(CountryNames , JsonRequestBehavior.AllowGet);
}
My Ajax call
#model Hotel.Models.Continent
<script>
$(document).ready(function () {
$("#Name").change(function () {
var ContinentoId = $(this).val();
$.ajax({
type: "POST",
dataType: "json",
data: { ContinentId: ContinentoId },
url: '#Url.Action("UpdateCountryDropDownList","Home")',
success: function (result) {
var Country = "<select id='ddlCountry'>";
Country = Country + '<option value="">--Select--</option>';
for (var i = 0; i < result.length; i++) {
Country = Country + '<option value=' + result[i].Value + '>' + result[i].Text + '</option>';
}
Country = Country + '</select>';
$('#Countries').html(Country);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(arguments)
}
});
});
})
</script>
My View
#using(Html.BeginForm()){
SelectList se = ViewBag.DropDownListOne;
#Html.DropDownListFor(x=>x.Name,se,"--Select--")
<div id ="Countries">
#Html.DropDownList("ddlCountry",new List<SelectListItem>(),"--Select--")
</div>
<input type="submit" value="submit" style="margin-top:100px;" />
}
HTTPPost Action
[HttpPost]
public string TwoDropDownList(string Name, string ddlCountry)
{
if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(ddlCountry))
{
return ("you must select Both");
}
else
return ("everything is working fine");
}
You already have a <select> element with name="ddlCountry" (generated by #Html.DropDownList("ddlCountry", new List<SelectListItem>(), "--Select--") but in the ajax call, you overwrite it and create a new <select> element without a name attribute (so its value is not posted back.
In the success callback, you should be creating <option> elements and appending them to the existing <select>
success: function (result) {
var country = $('#ddlCountry); // get the existing element
country.empty().append($('<option></option>').val('').text('--Select--'));
$.each(result, function(index, item) {
country.append($('<option></option>').val(item.Value).text(item.Text));
});
}
Side note: Your methods should be returning a collection of anonymous objects, not SelectListItem There is no point sending extra data (the other properties of SelectListItem) across the wire when you don't use them.
I think you are missing the end tag </div> for the <div id ="Countries">.
Try this:
<div id ="Countries">
#Html.DropDownList("ddlCountry",new List<SelectListItem>(),"--Select--")
</div>
I am working on an asp.net mvc web application. and i have a WebGrid, where i added a Page-size drop-down list to enable users to select how many records they like to have per page.
the Action method is:-
[OutputCache(CacheProfile = "NoCache")]
public ActionResult Disposed(string filter = null, int page = 1, int? pageSize = null, string sort = "Technology.Tag", string sortdir = "ASC")
{
GridList<DisposedResources> gridrecords = repository.GetDisposedResourcesForGrid(filter, page, pageSize, sort, sortdir, "rack");
ViewBag.PagedSizeOptions = new PageOptions().FilterOptions;
if (Request.IsAjaxRequest())
{
return PartialView("_disposed", gridrecords);
}
return View("Disposed", gridrecords);
}
and here is the repository method :-
public GridList<DisposedResources> GetDisposedResourcesForGrid(string filter, int page, int? pageSize, string sort, string sortdir, string resourcetype)
{
if (!pageSize.HasValue)
{
pageSize = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]);
}
var records = new GridList<DisposedResources>();
records.currentfilter = filter;
records.TotalRecords = GetDisposedResourcesForGridCount(filter, resourcetype);
records.hasNetworkInfo = false;
records.hasSystemInfo = false;
records.CurrentPage = page;
records.PageSize = pageSize.Value;
records.currentsort = sort;
records.currentsortdir = sortdir;
records.Content = tms.DisposedResources.Include(a=>a.Technology).Where(x => (filter == null ||
(x.Technology.Tag.ToLower().StartsWith(filter.ToLower()))
) && x.ResourceType.ToLower() == resourcetype.ToLower())
.OrderBy(sort + " " + sortdir)
.Skip((page - 1) * pageSize.Value)
.Take(pageSize.Value).ToList();
return records;
}
the Disposed view is :-
#model S.ViewModels.GridList<S.Models.DisposedResources>
Show #Html.DropDownList("FilterSize", new SelectList(ViewBag.PagedSizeOptions, "Value", "Text", ViewBag.pagesize ), new { #id= "FilterSize1",#class="SmallDropDown3"}) <span class="hidden-phone">per page.</span>
<div id="disposed">
#Html.Partial( "_disposed",Model)
</div>
#section Scripts {
<script type="text/javascript">
$("body").on('change', '#FilterSize1', function () {
//$(SizeProgressSort).show();
$.ajaxSetup({ cache: false });
$.ajax({
type: "Get",
url: '#Url.Action("Disposed")',
data: { pageSize: $('#FilterSize1').val(), page: "1", sort: $('#currentsort').val(), sortdir: $('#currentsortdir').val() },
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$('#disposed').html(data);
}
function errorFunc() {
alert('error');
}
});
</script>
}
and the _disposed partial view is:-
#model S.ViewModels.GridList<S.Models.DisposedResources>
var gridcolumns = new List<WebGridColumn>();
gridcolumns.Add(new WebGridColumn()
{
ColumnName = "Technology.Tag",
Header = Html.DisplayNameFor(model => model.Content.FirstOrDefault().Technology.Tag).ToString(),
CanSort = true
});
//code goes here...
var grid = new WebGrid(
canPage: true,
rowsPerPage: Model.PageSize,
canSort: true,
ajaxUpdateContainerId: "grid");
grid.Bind(Model.Content, rowCount: Model.TotalRecords, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(htmlAttributes: new { id = "grid" }, // id for ajaxUpdateContainerId parameter
fillEmptyRows: false,
tableStyle: "table table-bordered table-hover",
mode: WebGridPagerModes.All,
columns: gridcolumns
);
}
</div></div></div>
<input type="hidden" value="#Model.currentsort" id="currentsort" /> #Model.currentsort
<input type="hidden" value="#Model.currentsortdir" id="currentsortdir" /> #Model.currentsortdir
the problem i am facing is that the two parameters; currentsort + currentsortdir which are being passed as part of the javascript will not be changed,and the user will loose the current sort order if he chose to chnage the page size drop down-list. so can anyone advice what is the problem, now even if i chose to display the two values:-
Model.currentsort
&
Model.currentsortdir
they will always have the defualt value, although these values are being changed inside the repository method... but seems the partial view is somehow caching the old values for these two parameter ?
The ModelState is probably overriding the values you changed in your model. Call ModelState.Clear() in your action method and you should see the changed values.
I know that you have done the cache setting through ajaxSetup but try putting cache:false inside your script and see if that makes a difference.
$.ajax({
cache: false
type: "Get",
url: '#Url.Action("Disposed")',
--------