I have a function in c# that builds dictionary ,I need to pass this dictionary to my java-script function.
This is what I have tried
My server function
public partial class login : System.Web.UI.Page
{
protected Dictionary<string, string> GetTradingTypeToSelect()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
try {
string Types =GetString("some text);
var items = Types.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] { '=' }));
foreach (var item in items)
{
dict.Add(item[1], item[0]);
}
//this working 100%
}
catch (Exception ex)
{
}
return dict;
}
}
My client:
$(document).ready(function () {
$("#Account").keyup(function () {
var TradingTypeToSelect = '<%=GetTradingTypeToSelect();%>';
//TradingTypeToSelect is equals to string '<%=GetTradingTypeToSelect();%>'
var test = TradingTypeToSelect[0].key;
var test2 = TradingTypeToSelect[0].value;
});
});
What am I missing here?
You can create a [WebMethod] in the code behind and call it from javascript using $.ajax.Below is a complete example:
Code behind:
[System.Web.Services.WebMethod]
public static Dictionary<string, string> GetTradingTypeToSelect()
{
var dict = new Dictionary<string, string>();
dict.Add("1", "Item 1");
dict.Add("2", "Item 2");
return dict;
}
.ASPX:
<head runat="server">
<title></title>
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Account").keyup(function () {
$.ajax({
type: "POST",
url: "AjaxCallExample.aspx/GetTradingTypeToSelect",
contentType: "application/json;charset=utf-8",
success: function (data) {
alert(data.d["1"]);
alert(data.d["2"]);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="Account" type="text" />
</form>
</body>
How about exposing the dictionary in the view model:
public Dictionary<string, string> TradingTypesToSelect { get; set; }
And iterate over the dictionary inside the <script> block, creating a JavaScript associative array, like so:
<script>
var tradingTypesToSelect = {};
<% foreach (var tradingType in Model.TradingTypesToSelect) { %>
tradingTypesToSelect["<%= tradingType.Key %>"] = "<%= tradingType.Value %>";
<% } %>
</script>
At least this way you don't have to make another call (via AJAX) to retrieve additional data.
I believe you need to make a WebMethod to enable the server function to be called from the client side. Here is an example:
Calling ASP.Net WebMethod using jQuery AJAX
Related
I have an sql database with one table called "Tale", which has 2 rows: "ID", "Tale" containing 10 tales. I would like to list them to an HTML page. If I run the html, the result is "Undefined" ten times. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Mesék</title>
<link href="mesekStyle.css" rel="stylesheet" />
</head>
<body>
<p id="cim">Mesék</p>
<form>
<div id='meselist'>
</div>
<div>
<input id='meseText' type='text' placeholder='Ide írd a mesét' />
</div>
<button id='addButton' type='button' >Új mese felvétele</button>
</form>
<script>
document.getElementById('addButton').addEventListener('click', () => {
let data = {
meseText: document.getElementById('meseText').value
}
fetch('api/tales',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
).then(x => {
if (x.ok) {
alert('Siker');
} else {
alert('Kudarc');
}
});
});
function MeseBetöltés() {
fetch('api/tales')
.then(result => {
if (!result.ok) {
console.error(`Hibás letöltés: ${result.status}`);
return null;
} else {
return result.json();
}
})
.then(data => {
for (var i = 0; i < data.length; i++) {
document.getElementById("meselist").innerHTML += data[i].meseText += "<br/>"
}
})
}
window.onload = () => {
MeseBetöltés();
}
</script>
</body>
</html>
Also I tried adding new tales trough the textbox "meseText" and saving it with the button "addButton", and it works, it adds a new column to the SQL table but with the value NULL. Can you please help?
Here is the API Controller:
using HajosTeszt.MeseModels;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace HajosTeszt.Controllers
{
[Route("api/tales")]
[ApiController]
public class MeseController : ControllerBase
{
// GET: api/<MeseController>
[HttpGet]
public IEnumerable<Tale> Get()
{
MeseContext context = new MeseContext();
return context.Tales.ToList();
}
// GET api/<MeseController>/5
[HttpGet("{id}")]
public Tale Get(int id)
{
MeseContext context = new MeseContext();
var keresettMese = (from x in context.Tales
where x.Id == id
select x).FirstOrDefault();
return keresettMese;
}
// POST api/<MeseController>
[HttpPost]
public void Post([FromBody] Tale újMese)
{
MeseContext context = new MeseContext();
context.Tales.Add(újMese);
context.SaveChanges();
}
// PUT api/<MeseController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<MeseController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
MeseContext context = new MeseContext();
var törlendőMese = (from x in context.Tales
where x.Id == id
select x).FirstOrDefault();
context.Remove(törlendőMese);
context.SaveChanges();
}
[HttpGet]
[Route("count")]
public int M1()
{
MeseContext context = new MeseContext();
int mesékszáma = context.Tales.Count();
return mesékszáma;
}
}
}
Thank you very much.
Your mistake is in fetching the data
fetch(`{your backend base url}/api/tales`)
Explanation -> If you use /api/tales then the browser will interpret it as {your frontend base url}/api/tales therefore you need to specify the base URL, ie, {your backend base url}/api/tales
I'm trying to load a partial view and change it through a POST Ajax, but model doesn't update on view.
This is how I'm loading my partial:
#{
Html.RenderAction("UltimeNovità", "User");
}
and my action in UserController is:
public ActionResult UltimeNovità()
{
_UltimeNovitàViewModel model = new _UltimeNovitàViewModel();
model.NumeroPagina = 1;
return PartialView("~/Views/User/Partial/_UltimeNovità.cshtml",model);
}
and here the partial:
#model Mine.Models._UltimeNovitàViewModel
<script>
$(document).ready(function () {
});
function nextPage() {
$.ajax({
url: '#Url.Action("UltimeNovitàPaginaSuccessiva")',
type: 'POST',
data: { pagina: #Model.NumeroPagina },
success: function (data) {
$('#x').text('#Model.NumeroPagina');
},
error: function (xhr) {
alert('error');
}
});
}
</script>
<p id="x">1</p>
finally, the POST action in the same controller:
[HttpPost]
public ActionResult UltimeNovitàPaginaSuccessiva(int pagina)
{
_UltimeNovitàViewModel model = new _UltimeNovitàViewModel();
ModelState.Clear();
model.NumeroPagina = pagina + 1;
model.UltimeNovità = UserControllerMethods.GetUltimeNovità(model.NumeroPagina);
return PartialView("~/Views/User/Partial/_UltimeNovità.cshtml", model);
}
My problem is: why after the POST action #Model.NumeroPagina is always 1? I expect that each time I press the button which calls the function with ajax the #Model.NumeroPagina increases by 1 and it's shown in my paragraph.
The button is in the main page that contains the partial, actions are always hit and during debugging I can see that model.NumeroPagina is 2, but in view is always 1.
There are some issues in your code. I don't see where you're updating the HTML content, also you're generating the nextPage function eachTime, and others.
Check this sample, it should be easy to use.
Controller/ViewModel
public class NovitàController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult UltimeNovità(int? page)
{
var model = new UltimeNovitàViewModel
{
NumeroPagina = 1
};
return PartialView("_UltimeNovità", model);
}
[HttpPost]
public ActionResult UltimeNovitàPaginaSuccessiva(int pagina)
{
var model = new UltimeNovitàViewModel
{
NumeroPagina = pagina + 1,
UltimeNovità = GetUltimeNovità(pagina + 1)
};
return PartialView("_UltimeNovità", model);
}
public string GetUltimeNovità(int page)
{
return $"Ultime Novità: {page}"; //FOR DEMO
}
public class UltimeNovitàViewModel
{
public int NumeroPagina { get; set; }
public string UltimeNovità { get; set; }
}
}
_UltimeNovità partial view:
#model NovitàController.UltimeNovitàViewModel
#if (Model.UltimeNovità != null)
{
<div>
UltimeNovità: #Model.UltimeNovità
</div>
}
<div>
Pagina: #Model.NumeroPagina
</div>
<div>
<a class="next-page-link" href="#Url.Action("UltimeNovitàPaginaSuccessiva", "Novità", new {pagina = Model.NumeroPagina})">
Pagina Successiva
</a>
</div>
And the Index page:
#{
ViewBag.Title = "Novità";
}
<div id="RootDiv">
#{ Html.RenderAction("UltimeNovità", "Novità");}
</div>
#section scripts{
<script>
$(function() {
function bindNextPageLink() {
$("#RootDiv a.next-page-link").click(function(event) {
event.preventDefault();
$.post($(this).attr("href"),
function(data) {
$("#RootDiv").html(data);
bindNextPageLink();
}
);
});
}
bindNextPageLink();
});
</script>
}
I tried to write the example very similar to your code.
I am trying to filter datatable by select.
I can see the data in select but don't know how to filter it.
Here's my code.
Thanks
function getSearchList() {
$.post('#(Url.Action("GetSearchList", "ESR"))')
.success(function (data) {
if (data.length > 0) {
$.each(data, function () {
$('#Search_Id').append($('<option>', {
value: this.ID,
text: this.S_ID
}));
});
}
$(window).unblock();
})
}
and
$(document).ready(function () {
$('#Search_Id').select2({
placeholder: "Search",
allowClear: true,
});
});
and
<div class="col-sm-2">
<select class="select" id="Search_Id"></select>
</div>
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
public List<SearchId> GetSearchIdData()
{
string strSQL = string.Format(#"SELECT ID, S_ID FROM TBR");
using (var conn = SqlUtility.GetDBConnection())
{
conn.Open();
return conn.Query<SearchId>(strSQL).ToList();
}
}
and
public ActionResult GetSearchIdList()
{
JsonResult result;
List<SearchId> List = service.GetSearchIdList();
result = Json(List);
result.MaxJsonLength = int.MaxValue;
return result;
}
and
public class SearchId
{
public int ID { get; set; }
public string S_ID{ get; set; }
}
and
public List<SearchId> GetSearchIdList()
{
return repo.GetSearchIdData();
}
I am new to both asp.net MVC and JQuery so be gentle.
I am trying to use a HTTP Post to update my contact form, used to send an email, using AJAX. I have seen lots of posts but what I want seems specific and I cant seem to find anything relevant.
The down low: I have a layout page which has the header, renders the body and has my footer in. My footer contains the form I want to submit. I want to submit this form without refreshing the whole page. The layout page:
<div id="footer">
#{Html.RenderAction("Footer", "Basic");}
</div>
<p id="p"></p>
I have a model for this form to send an email.
namespace SimpleMemberShip.Models
{
public class EmailModel
{
[Required, Display(Name = "Your name")]
public string FromName { get; set; }
[Required, Display(Name = "Your email"), EmailAddress]
[StringLength(100, ErrorMessage = "The email address entered is not valid")]
public string FromEmail { get; set; }
[Required]
public string Message { get; set; }
}
The footer:
<h2> footer yo !</h2>
#Html.ValidationSummary()
<fieldset>
<legend>Contact Me!</legend>
<ol>
<li>
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail)
</li>
<li>
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName)
</li>
<li>
#Html.LabelFor(m => m.Message)
#Html.TextBoxFor(m => m.Message)
</li>
</ol>
<button id="submit"> Submit </button>
</fieldset>
controller:
[ChildActionOnly]
public ActionResult Footer()
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
[HttpPost]
public ActionResult Footer(EmailModel model)
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
I want to use the model validation and everything to be the same or similar as if the form was posted normally through the server.
Edit:
My new code, which works great! but it only works once, when the button is clicked again nothing happens. Anyone know why?
<script type="text/javascript">
$("#submit").click(function () {
$("#footer").html();
var url = '#Url.Action("Footer", "Basic")';
$.post(url, { FromName: $("[name=FromName]").val(), FromEmail: $(" [name=FromEmail]").val(), Message: $("[name=Message]").val() }, function (data) {
$("#footer").html(data);
});
var name = $("[name=FromName]").val();
$("#p").text(name);
});
</script>
new Edit:
did some research and using
$("#submit").live("click",function () {
instead of
$("#submit").click(function () {
seemed to do the trick.
<script type="text/javascript">
$("#submit").live("click",function () {
$('.validation-summary-errors').remove();
var url = '#Url.Action("Footer", "Basic")';
$.post(url, { FromName: $("[name=FromName]").val(), FromEmail: $("[name=FromEmail]").val(), Message: $("[name=Message]").val() }, function (data) {
$("#footer").html(data);
});
});
</script>
ended up with this but will try the "serialize()" option next time.
controller was changed to this without the [ChildActionOnly] and works perfect now
[HttpPost]
public ActionResult Footer(EmailModel model)
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
Thank you everyone that helped!
Change the [ChildActionOnly] to [HttpGet] in the controller
You can pass model data to controller by doing the following steps
1. Get the input values on click of submit and sent to the Footer action in controller
$("#submit").click(function () {
var FromEmailValue = $('#FromEmail').val();
var FromNameValue = $('#FromName').val();
var MessageValue = $('#Message').val();
var url = '#Url.Action("Footer", "Basic")';
$.ajax({
url: urlmodel,
data: { FromName: FromNameValue, FromEmail: FromEmailValue, Message: MessageValue},
cache: false,
type: "POST",
success: function (data) {
do something here
}
error: function (reponse) {
do something here
}
});
});
In the controller
``
[HttpGet]
public ActionResult Footer()
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
[HttpPost]
public ActionResult Footer(string FromName = "", string FromEmail = "", string Message = "")
{
//for ajax request
if (Request.IsAjaxRequest())
{
do your stuff
}
}
I want to show address in my database to an autocomplete aui input field.Everything seems working fine.But im not able to retrive the address number of the record.How to use the on change event of autocomple-list or how can i access the selected item's json object
#Override
public void serveResource( ResourceRequest resourceRequest, ResourceResponse resourceResponse ) throws IOException,
PortletException
{
String cmd = ParamUtil.getString(resourceRequest, "get_address");
String myInputNode = ParamUtil.getString(resourceRequest, "addressAutocomplete");
System.out.println("addressAutocomplete"+myInputNode);
if (cmd.equals("get_address")) {
getUsers(resourceRequest, resourceResponse,myInputNode);
}
}
private void getUsers(ResourceRequest resourceRequest, ResourceResponse resourceResponse, String myInputNode) throws IOException, PortletException {
JSONArray usersJSONArray = JSONFactoryUtil.createJSONArray();
ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
JSONObject userJSON=null;
try {
List<AddressMaster> userList=AddressMasterLocalServiceUtil.getAllAddressBySearchKey( myInputNode );
for(AddressMaster addressMaster:userList){
userJSON=JSONFactoryUtil.createJSONObject();
userJSON.put("addressNumber",addressMaster.getAdrNummer());
userJSON.put( "address", addressMaster.getAddress())
);
usersJSONArray.put(userJSON);
}
} catch (Exception e) {
}
PrintWriter out=resourceResponse.getWriter();
out.println(usersJSONArray.toString());
System.out.println("usersJSONArray"+usersJSONArray.toString());
}
Jsp File
<portlet:resourceURL var="getAddress">
<portlet:param name="get_address" value="get_address" />
</portlet:resourceURL>
<aui:input id="addressAutocomplete" name="addressAutocomplete" label="group_choose_address" style="width:700px"/>
<aui:script>
AUI().use('autocomplete-list','aui-base','aui-io-request','autocomplete-filters','autocomplete-highlighters',function (A) {
A.io.request('<%=getAddress%>',{
dataType: 'json',
method: 'GET',
on: {
success: function() {
//continents=this.get('responseData');
//alert(continents[0].name);
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'true',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace/>addressAutocomplete',
resultTextLocator: 'address',
resultHighlighter:['phraseMatch'],
resultFilters:['phraseMatch'],
render: 'true',
source:this.get('responseData'),
});
}}
});
});
</aui:script>
It's a bit tricky to see exactly what'll be coming, but I think you could do:
var address_ac = new A.AutoCompleteList({... as you have it...});
address_ac.on('select', function (e) {
var selected_node = e.itemNode,
selected_data = e.result;
});
Docs here: http://alloyui.com/versions/1.5.x/api/classes/AutoCompleteList.html#events