问题描述
我想让我的模型由view元素的值设置。 然后使用javascript中的model属性值作为参数调用控制器中的方法。
最好的方法是什么?
就像是:
@Model.Attribute = $(ElementId).val(); //<- how can I do this?
'@Html.Action("GetPeople", new { id = @Model.Attribute})';
我一直在调查,但找不到解决方法。 我阅读并尝试在视图和模型之间进行绑定。 但是当我调用@ Model.Attribute时,该值始终是默认值。 即使我更改了文本框值,并且model属性也没有更改。
@Html.TextBoxFor(m => m.Code, new { id = "txtAttribute"})
如您所见,我在Controller中进行了模型属性绑定
public ActionResult Index()
{
var model = new MyModel();
View("Default", model);
}
我尝试了很多事情,但都失败了
var modelattribute = '@Model.Attribute';
modelattribute = '@ViewData["ModelAttribute"]';
modelattribute = '@Html.Raw(Model.Attribute)'
modelattribute = '@Html.raw(json.encode(Model.Attribute))'
这可能吗? 还是我必须更改算法?
更新:我的模型代码
public class MyModel
{
public string Attribute{ get; set; }
}
非常感谢,尼尔森
1楼
您可以通过以下方式设置javascript变量的值: var modelattribute = "@Model.Attribute";
至于将模型数据发送到控制器,到目前为止,最简单的方法是使用隐藏的表单元素:
//JAVASCRIPT
function postDataToController() {
var form = document.createElement("form");
form.setAttribute("action", "submitFormData");
var hiddenElement = document.createElement("input");
hiddenElement.setAttribute("name","attributeName");
$(hiddenElement).val("attribute value");
$(form).append(hiddenElement);
$(form).submit();
}
//C#
[HttpPost]
public void submitFormData(MyModel model) {
System.Collections.Specialized.NameValueCollection nvc = Request.Form;
model.Attribute = nvc["attributeName"];
}