[英]How can I pass a value from my page to the controller?
I'm using MVC with Razor and C#. 我在Razor和C#中使用MVC。 I would like to update an element... a counter with ajax.
我想更新一个元素... ajax计数器。 Here is my code:
这是我的代码:
@model Domain.CounterObject
@using (Ajax.BeginForm("Count", "CounterObject", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "my-control" }))
{
<div id="my-control" class="bid-object">
<div>
<span class="title">@Html.Encode(Model.Title)</span>
</div>
<div>
<span class="display">@Html.Encode(Model.GetFinalDate())</span>
</div>
<div>
<span class="display">@Html.Encode(Model.GetValue())</span>
</div>
<div>
<input type="submit" value="Count" />
</div>
</div>
}
In my controller I have this code: 在我的控制器中,我有以下代码:
[HttpPost]
public PartialViewResult Count(CounterObject counter)
{
// Special work here
return PartialView(counter);
}
The problem is that my CounterObject counter I receive in my Count method is always null. 问题是我在Count方法中收到的CounterObject计数器始终为null。 How can I pass a value from my page to the controller?
如何将值从页面传递到控制器?
You'll have to define a input field with a name and id that the ModelBinder can then Bind to your CounterObject. 您必须定义一个名称和ID的输入字段,然后ModelBinder可以将其绑定到CounterObject。
You could use @Html.EditorForModel once and then inspect the generated Html to see what kind of name/id pairs it is generating. 您可以使用@ Html.EditorForModel一次,然后检查生成的HTML以查看其生成的名称/标识对类型。 With those you can go on and handcraft your Html if you wanted to.
有了这些,您可以继续手工制作HTML。
use 采用
<span class="title">@Html.Encode(Model.Title)</span>
<div class="editor-field">@Html.EditorFor(Model => Model.Title)<div>
//For other fields
In this way you can bind to your object. 这样,您可以绑定到对象。
I receive in my Count method is always null
我收到的Count方法始终为null
First of all you are not submitting anything from the form then how does the binding happens? 首先,您不提交表单中的任何内容,然后绑定如何发生? If the user is not allowed to edit the values but still you want to submit them through the form then you have to use
hidden fields
along with them. 如果不允许用户编辑值,但是您仍想通过表单提交值,则必须将
hidden fields
与它们一起使用。
For ex. 对于前。
<div>
<span class="title">@Html.Encode(Model.Title)</span>
@Html.HiddenFor(m => m.Title)
</div>
Note that the hidden fields should have the same names as the properties to make the binding happen successfully. 请注意,隐藏字段的名称应与属性相同,以使绑定成功进行。
It is better to have properties in the Model that store the GetFinalDate()
and GetValue()
results so you can easily bind the things like in Title
. 最好在Model中具有存储
GetFinalDate()
和GetValue()
结果的属性,以便您可以轻松绑定Title
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.