我想要的是将View中的txtComments值(使用jquery / ajax)传递给Controller。
问题是ajax / jquery不接受脚本标记作为字符串。这意味着,当我在txtComments中输入任何脚本/ html标签时,ajax会进入错误功能而无法进入控制器。
这是jQuery:
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>?id=' + selectedId + '&comments=' + escape(comments),
type: "post",
cache: false,
success: function (savingStatus) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
这是控制器:
[HttpPost]
public ActionResult SaveComments(int id, string comments){
var actions = new Actions(User.Identity.Name);
var status = actions.SaveComments(id, comments);
return Content(status);
}
我也试过$('#txtComments').serialize()
而不是逃避(评论),但仍然是一样的。
答案 0 :(得分:49)
尝试使用data
功能的$.ajax
选项。更多信息here。
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatus) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
答案 1 :(得分:7)
这是执行相同调用的另一种方法。你的类型应该总是在CAPS中,例如。键入:“GET”/类型:“POST”。
$.ajax({
url:/ControllerName/ActionName,
data: "id=" + Id + "¶m2=" + param2,
type: "GET",
success: function(data){
// code here
},
error: function(passParams){
// code here
}
});
另一种选择是在链接上使用data-ajax。
<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>
假设你有一个带有我__tent的div,这将调用该动作并用该动作返回的数据替换该div中的内容。
<div id="_content"></div>
不是你问题的直接答案,但是你应该注意的一些信息;)。
答案 2 :(得分:5)
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatu`enter code here`s) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
答案 3 :(得分:0)
View Data
==============
@model IEnumerable<DemoApp.Models.BankInfo>
<p>
<b>Search Results</b>
</p>
@if (!Model.Any())
{
<tr>
<td colspan="4" style="text-align:center">
No Bank(s) found
</td>
</tr>
}
else
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Postcode)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Postcode)
</td>
<td>
<input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />
</td>
</tr>
}
</table>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSearch").off("click.search").on("click.search", function () {
if ($("#SearchBy").val() != '') {
$.ajax({
url: '/home/searchByName',
data: { 'name': $("#SearchBy").val() },
dataType: 'html',
success: function (data) {
$('#dvBanks').html(data);
}
});
}
else {
alert('Please enter Bank Name');
}
});
}
});
public ActionResult SearchByName(string name)
{
var banks = GetBanksInfo();
var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList();
return PartialView("_banks", filteredBanks);
}
/// <summary>
/// Get List of Banks Basically it should get from Database
/// </summary>
/// <returns></returns>
private List<BankInfo> GetBanksInfo()
{
return new List<BankInfo>
{
new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220" },
new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117" },
new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061" },
new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061" },
new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061" }
};
}
答案 4 :(得分:0)
Configuration:
Cluster: disabled
Tenant: master
Mode: development
OS: Mac OS X 10.13.6, x86_64
Database: Pool: hybris - hsqldb, table prefix:
SA - jdbc:hsqldb:file:/Users/abcd/Hybris/hybris/data/hsqldb/mydb;shutdown=true;hsqldb.tx=MVCC
Platform: 6.6.0.4
Java: Oracle Corporation
Java(TM) SE Runtime Environment, 1.8.0_191-b12
/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/jre
VM Locale: language=en,country=US,region=null
Cache: RegionCache is not yet initialized. [de.hybris.platform.cache.impl.RegionCacheAdapter]
Server type: tomcat
答案 5 :(得分:0)
我不想再提出威胁,因此请在这里张贴我的问题
Ajax不会将值转发给控制器,而我只是找不到错误:(
-JS
<script>
$(document).ready(function () {
$("#sMarka").change(function () {
var markaId = $(this).val();
alert(markaId);
debugger
$.ajax({
type:"POST",
url:"@Url.Action("VratiModele")",
dataType: "html",
data: { "markaId": markaId },
success: function (model) {
debugger
$("#sModel").empty();
$("#sModel").append(model);
}
});
});
});
</script>
-控制器
public IActionResult VratiModele(int markaId = 0)
{
if (markaId != 0)
{
List<Model> listaModela = db.Modeli.Where(m => m.MarkaId == markaId).ToList();
ViewBag.ModelVozila = new SelectList(listaModela, "ModelId", "Naziv");
}
else
{
ViewBag.Greska = markaId.ToString();
}
return PartialView();
}