[英]How to pass the div value not part of model to backend controller method
Question: I want to have one div in UI and I want to render some value into it via JQuery and when I submit the form I should be able to access it in the backend . 问题:我想在UI中有一个div,并且希望通过JQuery在其中呈现一些值,并且当我提交表单时,我应该能够在后端访问它。
View: 视图:
@model ScheduleAptMV
using (Html.BeginForm())
{
////// I want a div here /////
@Html.LabelFor(model => model.FirstName })
@Html.EditorFor(model => model.FirstName)
<input type="submit" value="Make Appointment"/>
}
}
Model: 模型:
public class ScheduleAptMV
{
public string FirstName {get; set;}
}
Controller: 控制器:
[HttpPost]
public ActionResult SaveDelayedPayment(ScheduleAptMV data)
{
// I want to be able to access the Div text too
}
Partial Solution 1: 部分解决方案1:
I added a div 我添加了一个div
<div id="totalAmount"></div>
And with Jquery I added something like 并用Jquery我添加了类似
$("#totalAmount").text("HelloFoo");
But my problem is it is not tied to the model, so how to send it to the backend. 但是我的问题是它不依赖于模型,因此如何将其发送到后端。
Partial Solution 2: 部分解决方案2:
I can create a property in my model which will represent that div content so that it gets Strongly Bound. 我可以在模型中创建一个属性 ,该属性将表示该div内容,从而使其牢固地绑定。 This value is just for display user should not be allowed to edit it, only it should by rendered by Jquery code. 此值仅用于显示, 不应允许用户编辑它,而应由Jquery代码呈现。 I can use 我可以用
@Html.DisplayFor()
Something like below: 如下所示:
New Model: 新模型:
public class ScheduleAptMV
{
public string FirstName {get; set;}
public decimal totalAmount{get; set;}
}
New View: 新视图:
<span class="myClass">
@Html.DisplayFor(model => model.totalAmount)
</span>
Question: But now how to render this property using Jquery . 问题:但是现在如何使用Jquery 呈现此属性。 Do I need to use something else apart from DisplayFor
. 我是否需要使用DisplayFor
以外的其他工具。
Edit: This is how the DisplayFor
renders currently. 编辑:这是DisplayFor
当前呈现的方式。
<span class="myClass">
0.00
</span>
Question: If I follow soution 2 then how to attach a class to DisplayFor
Element. 问题:如果我遵循第2部分,那么如何将类附加到DisplayFor
Element。
Solution 1 解决方案1
Change your action signature to 将您的动作签名更改为
public ActionResult SaveDelayedPayment(ScheduleAptMV data, int totalAmount)
however it must be a POSTable entity, eg a textbox, not a div. 但是,它必须是POSTable实体,例如文本框, 而不是 div。 So add a hidden input: 因此,添加一个隐藏的输入:
<input type='hidden' name='totalAmount' id='totalAmount'/>
<div id='totalAmountDisplay'></div>
and set accordingly: 并据此设置:
$("#totalAmountDisplay").text("1024");
$("#totalAmount").val(1024);
Solution 2 解决方案2
Similar to solution 1, you just need a hidden input so that it can be POSTed: 与解决方案1相似,您只需要一个隐藏的输入即可将其发布:
@Html.HiddenFor(m => m.totalAmount)
ensure that's within the <form>
and it will be bound automatically. 确保在<form>
,并且它将被自动绑定。 Add the display using .DisplayFor
or however else you like and jquery to update (if required) similar to above. 使用.DisplayFor
添加显示,或者使用其他类似的方法和jquery进行更新(如果需要),类似于上述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.