从 JavaScript 值分配模型属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11858755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign Model property value from JavaScript value
提问by csefaruk
I have a model with the following definition:
我有一个具有以下定义的模型:
namespace ESimSolChemical.Models
{
public class Employee
{
public int EmployeeID{ get; set; }
public string EmployeeName{ get; set; }
public string Age{ get; set; }
public string Address{ get; set; }
}
I have Following JavaScript:
我有以下 JavaScript:
<script type="text/javascript">
$(function () {
$('#btnEmployeePiker').click(function () {
var oParameter = new Object();
oParameter.MultipleReturn = false;
var oReturnObject = window.showModalDialog('/Employee/EmployeePiker/', oParameter, 'dialogHeight:470px;dialogWidth:550px;dialogLeft:400;dialogTop:100;center:yes;resizable:no;status:no;scroll:no');
});
});
</script>
My Javascript oReturnObject
contains two property Like :
我的 JavascriptoReturnObject
包含两个属性,例如:
oReturnObject.EmployeeID;
oReturnObject.EmployeeName;
Now I would like to assign:
现在我想分配:
@Model.employeeID= oReturnObject.EmployeeID;
How can I accomplish this task?
我怎样才能完成这个任务?
回答by Brendan Vogt
You cannot set server side values with Javascript. You could bind these values to input fields like textboxes or hidden fields and then use Javascript to modify these values of these input fields.
您不能使用 Javascript 设置服务器端值。您可以将这些值绑定到文本框或隐藏字段等输入字段,然后使用 Javascript 修改这些输入字段的这些值。
Take a look at these articles, it might help you out:
看看这些文章,它可能对你有帮助:
回答by twoflower
You can't execute a server-side code like that in JavaScript.
你不能像 JavaScript 那样执行服务器端代码。
You need to somehow post the updated values back to the server to process them.
您需要以某种方式将更新后的值发布回服务器以处理它们。
Take a look at KnockoutJS, it makes things like this very easy. Basically, you will just serialize your model class on the client side to a JavaScript object, work with it until you decide to save it back and then you send it to the server as JSON, which will allow you to have an action method like this
看看KnockoutJS,它使这样的事情变得非常容易。基本上,您只需将客户端的模型类序列化为 JavaScript 对象,使用它直到您决定将其保存回来,然后将其作为 JSON 发送到服务器,这将允许您拥有这样的操作方法
public ActionResult UpdateEmployee(Employee employee)
{
// Update the database...
//
}
The page linked above has plenty of tutorials to start with.
上面链接的页面有很多教程可以开始。
回答by Dev Kumar
This is what I have used:
这是我用过的:
@{
@Convert.ToString("var refID = " + @Model.RefID + ";alert(refID);")
}
and its working fine.
并且它工作正常。