Call codebehind function from javascript with parameter - javascript

I need call codebehind function with parameter which is instance of some Entity class from script tags in aspx page. Im created popup windows from kendo ui using kendotemplate and in this template i need my form with inputs and button used in code behind. Something like this http://demos.telerik.com/kendo-ui/grid/custom-command but when i add asp items to template tags not work for me.
My entity:
public class Person
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
public int Age { get; set; }
}
code behind function:
protected void btnAddPerson_Click(object sender, EventArgs e)
{
Person p= new Person();
// get values from three inputs
p.FirstName= personFirstName.Value;
p.LastName= personLastName.Value;
p.Age = Convert.ToInt32(personAge.Value);
...
}
i need in javascript something like this:
<script type="text/x-kendo-template" id="template">
<Asp:Input ...>
<Asp:Input ...>
<Asp:Input ...>
<Asp:Button ...>
</script>
and sorry for my english

Related

Trying to post a list collection to the controller with ajax

I'm trying to post a list collection to the controller with a full page post back to the server. The data from the client side is written with JavaScript / jQuery and the server code is written in C# using ASP.Net MVC.
I'm not sure what the issue is because when the ItemCheck method is hit with a breakpoint on the first curly brace after the method name but the model object Items property is null even though it's in the form data mentioned further below.
The code below is simplified for ease and is not working.
Input hidden field in the view where the JavaScript adds an item to it each time add button is pressed.
#model UI.ViewModels.ItemResource
#Html.HiddenFor(model => model.Items, new { #id = "Items" })
<button class="btn-default btn" id="AddItem" name="AddItem" type="button" disabled>Add</button>
JavaScript
var items = [];
// This code only adds an item to the items collection input hidden
// field for a full page post back to the server.
var addItemToList = function () {
var item = {
ItemDate: $(date).val(),
ItemAmount: $(amount).val()
};
items.push(item);
$("#Items").val( JSON.stringify(items));
};
Controller
public ActionResult ItemCheck(ItemViewModel model)
{
if (result.IsValid)
{
model.Items = _anotherViewModel.Items;
_anotherViewModel.Items= null;
model.IsValid = _itemService.Save(model, _Itemhelper.GetUserId());
}
else
{
//Validation here
}
return View(model);
}
ViewModels
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace UI.ViewModels.ItemResource
{
public class ItemsViewModel
{
public ItemsViewModel()
{
Items = new List<ItemViewModel>();
}
[JsonBindable]
public List<ItemViewModel> Items { get; set; }
}
public class ItemViewModel
{
public DateTime ItemDate { get; set; }
public decimal ItemAmount { get; set; }
}
}
FormData
Items: [{"ItemDate":"2020-06-05","ItemAmount":"2267"}]

Using C# MVC multiple dynamic models in View

I have a View with several form that I'm using for searching and displaying the results as partial View in like SearchByNumber, SearchByVehicle, etc.
I'm trying to load view and execute search for different forms by posting link with querystring like www.example.com/Search?number=101010 from different view.
For the first form, SearchByNumber I only have one parameter, string number and i'm returning view with dynamic Model and its working like it should, but I only manage to make search for this form.
Here is my controller:
public ActionResult Index(string number)
{
return View(model: number);
}
and in the View I have:
<form id="searchbynumberform">
Search By Any Number:
<div class="input-group input-group-sm">
<input type="text" class="form-control" name="number" id="number" value="#Model">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" name="numbersearch" id="numbersearch" disabled>
Search
</button>
</span>
</div>
</form>
My Question is, if anyone can help me, How to perform search let's say on the second form where I have int type and string name parameters?
Thank You in advance...
At the moment your Model is only the search string that was entered, which seems rather incomplete. It would make a lot more sense if the Model also contained the actual search results, which after all is what the user wants to see. And then you can also add the other search properties.
The MVC approach for this is to create a (View)Model class, somewhere in your project, something like this:
public class SearchModel
{
public string Number { get; set; }
public int? Type { get; set; }
public string Name { get; set; }
public List<SearchResult> SearchResults { get; set; }
}
And then use it e.g. like this:
public ActionResult Index(string number)
{
var model = new SearchModel
{
Number = number,
SearchResults = GetByNumber(number)
};
return View(model);
}
public ActionResult IndexOther(int type, int name)
{
var model = new SearchModel
{
Type = type,
Name = name,
SearchResults = GetByTypeAndName(type, name)
};
return View(model);
}
And in your Index.cshtml:
#model SearchModel
#* You can now use Model.Number, Model.Type, Model.Name and Model.SearchResults. *#

Use javascript variable in c#

Is it possible to use js variables in c# code?
This is my model:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual ICollection<Department> Parent { get; set; }
}
And this is my cshtml:
#model List<inspinia.models.Department>
<select name="DepartmentId" class="form-control" id="Department">
#foreach (var item in Model)
{
<option value="#item.Id">#item.Name</option>
}
</select>
<script>
$(document).ready(function () {
$("#Department").on("change", function () {
var DepartmentId = $('option:selected', this).attr('value');
//the problem in the next line.
#foreach(var item in Model.Where(x=>x.ParentId==#:DepartmentId))
{
#:alert(#item.id)
}
});
});
</script>
Well I am having error when I use
Model.Where(x=>x.ParentId==#:JAVASCRIPT VARIABLE).
Is there any way to do it or I definitely have to use ajax ?
No you can't, because the javascript code's is for clientside and razor in serverside.
You have two solutions:
1- Put all departement in list(<ul>) and use JQuery for get your data on change
2- Use jquery ajax and get data directly from controller(create controller for that)

How to assign value in $(document).ready from code behind

i'm developing a .net application using twitter bootstrap.
I'm trying to get data from .aspx.cs page to .aspx page.
Please find my code below:
strOblect.cs
public class strObject
{
public string Name { get; set; }
public string Description { get; set; }
}
.aspx.cs page:
public List<strObject> stringList = new List<strObject>();
protected void Page_Load(object sender, EventArgs e)
{
strObject ObjOne=new strObject();
ObjOne.Name="One";
ObjOne.Description ="One";
stringList.Add(ObjOne);
strObject ObjTwo=new strObject();
ObjTwo.Name="Two";
ObjTwo.Description ="Two";
stringList.Add(ObjTwo);
strObject ObjThree=new strObject();
ObjThree.Name="Three";
ObjThree.Description ="Three";
stringList.Add(ObjThree);
}
.aspx:
<asp:Panel ID="pnlData" runat="server" style="background-color:White;">
<script type="text/javascript">
$(document).ready(function () {
var valueAssigned=stringList;
});
</script>
</asp:Panel>
I'm unable to get stringList value in $(document).ready.
Please help me out to get the value.
It appears that your stringList is actually a collection of objects. In order to use it in JavaScript as such, you'll need to serialize it to a javascript object.
var valueAssigned=<%=new JavaScriptSerializer().Serialize(stringList)%>;
So that you can wind up with the following:
var valueAssigned= [{Name: "Foo", Description: "Bar"}, {...}];
Edit
JavaScriptSerializer is in System.Web.Script.Serialization - you'll either need to add this below at the top of your <%# Page
<%# Import Namespace="System.Web.Script.Serialization" %>
or specify the FQ name
var valueAssigned=<%=new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(stringList)%>;
StuartLC's answer will be enough.JSON is very good option for that purpose. Other option can be to register client script in aspx.cs. Here is another SO question regarding that
How do I pass data from c# to jquery/javascript?

Javascript updates not posted, properties have default value on binding

I'm struggling with this issue since yesterday.
I have a simple ViewModel :
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
[Required]
public double Longitude { get; set; }
[Required]
public double Latitude { get; set; }
}
And this form :
<h2>#ViewBag.Title.</h2>
<div class="row">
<div class="col-md-8">
<section id="loginForm">
#using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(x => x.Latitude)
#Html.TextBoxFor(x => x.Longitude)
}
And this javascript that is updating the textbox with user's location.
<script type="text/javascript">
$(document).ready(function () {
navigator.geolocation.getCurrentPosition(getPosition);
});
function getPosition(position) {
document.getElementById("Latitude").value = position.coords.latitude;
document.getElementById("Longitude").value = position.coords.longitude;
}
<script>
And here is my action :
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return View()
}
What really drives me crazy is that I can see that the textbox is properly filled with the coordinates in the browser, however nothing is received on the controller. All the properties : email, password, rememberbe etc... are correctly binded but these two. That's really weird.
Please I really need to solve that. Any help would be appreciated
Well I got it. It has nothing to do with javascript mechanisms, actually the problem was the delimiter for the number. By default javascript delimited the decimal part with a ".", I had to change it to a ",". I really hope it will save someone's else time.
I've never came accross this problem before, but I can't remember having posted double values in the past. We learn something new everyday.

Categories