[英]c # variable assignment from javascript variable error (CS1002:; expected)
我正在尝试从ASP.Net MVC中的javascript变量分配ac#变量。 但是我收到“ CS1002 :;预期”错误。
function openEditJoining(joining_id) {
@{
int joiningId = @:joining_id ;
}
}
C#和JS在不同的地方处理,因此您不能直接将JS中的变量分配给c#
其他选项:
C#代码是服务器端代码,这意味着它在服务器上运行。 JavaScript代码在浏览器中运行。
整个周期如下:
请求进入->所有C#代码都被执行->呈现的结果被发回
因此,您可以执行以下操作(在.cshtml
):
function openEditJoining(joining_id) {
return @Model.JoiningId;
}
C#代码将首先运行,并假设JoiningId = 56
,然后返回的结果将是:
function openEditJoining(joining_id) {
return "56";
}
这是完全有效的,因为首先执行服务器端代码。 但是,您正在尝试另一种方法,这是非法的。 一旦结果返回给客户端,它就不是C#。 现在都是客户端。
您可以做的是,可以使用查询字符串或请求正文在请求中发送变量。 例如,以localhost:49976/[controllerName]/joinings?id=56
身份发送请求,并在该控制器内部,将操作方法的签名更改为:
public IActionResult Joinings(int id) {
}
现在, id
参数将获取在查询字符串中发送的值。 当然,只要查询字符串和method参数中定义的id
就可以将id
命名为任意名称。 或者,您可以在请求正文中发送数据(例如,使用POST
或PUT
)。 希望能有所帮助。
为什么不从隐藏字段中获得此值? 像https://jsfiddle.net/Alan_van_Buuren/7kg99kh3/
<div class="container">
<h3>Why don't get this value from a hidden field? like</h3>
<p>I see your question in: https://stackoverflow.com/questions/46040155/c-variable-assignment-from-javascript-variable-error-cs1002-expected</p>
<div>
<div class="form-group">
<label>Your value :</label>
<input type="text" id="field" class="form-control" />
<input type="hidden" id="yourFieldInModel" class="form-control" />
</div>
<button class="btn btn-info">Send to model...</button>
</div>
<p id="valueHidden">The value is: </p>
</div>
<script>
//Method that assign your frontValue into a field in model
function getSome(valueFromModel) {
// TODO: anything
$('#yourFieldInModel').attr('value', valueFRomModel);
}
$(document).ready(function() {
$('#field').on('change', function() {
var thisValue = $(this).val();
$('#valueHidden').text('The value is ' + thisValue);
getSome(thisValue);
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.