gpt4 book ai didi

c# - MVC 中的动态表单数据

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:00 24 4
gpt4 key购买 nike

我正在创建一个简单的调查系统,目前正在生成这样的 HTML。如果解决方案需要,这当然可以更改。

<form id="surveyForm"> 
<input type="hidden" value="1" name="surveyId" />
<div class="questionContainer">
<h4>What is 2 + 2?</h4>
<div class="optionsContainer">
<div class="optionContainer">
<input id="option_1" value="1" type="radio" name="question_1" />
<label for="option_1">3</label>
</div>
<div class="optionContainer">
<input id="option_2" value="2" type="radio" name="question_1" />
<label for="option_2">4</label>
</div>
<div class="optionContainer">
<input id="option_3" value="3" type="radio" name="question_1" />
<label for="option_3">5</label>
</div>
</div>
<div class="freeTextContainer">
<h4>Comments:</h4>
<textarea id="freetext_1" name="freetext_1"></textarea>
</div>
</div>
<!-- Multiple questionContainer may follow -->
</form>

如您所见,我最终得到了一些 POST 变量,即 question_1question_2 等,以及 freetext_1freetext_2 等等。单选按钮的值对应于在后端数据库中找到的选项 ID。

现在我想使用 jQuery 或类似工具将使用 Ajax 的响应发布到 MVC API Controller 。

所以问题1;我如何使用 jQuery 将这些值序列化为我可以在服务器端解码的 JSON 字符串,以及如何指定接受此 json 字符串的 MVC 方法服务器端?

问题 2:上面建议的解决方案不是很优雅,我想以一种可以转换为 POCO 对象结构的方式对其进行序列化,该结构可用作 MVC API 方法中的输入参数,例如:

public class SurveyAnswer
{
public int SurveyId { get; set; } // From a hidden field
public List<QuestionAnswer> Answers{ get; set; }
}

public class QuestionAnswer
{
public int QuestionId { get; set;}
public int OptionSelecion { get; set; }
public string FreeText { get; set; }
}

然后是像这样的 MVC 方法:

[HttpPost]
public ActionResult PostAnswer(SurveyAnswer answer)
{
...
}

我将如何序列化表单以实现上述目标?

最佳答案

您可以使用以下代码序列化表单。

var formData = $("#surveyForm").serialize();

您可以像这样用 jQuery post 发送它

$.post('@Url.Action("Save", "ApiController")', $(this).serialize(), function(json) {
// handle response
}, "json");

那么如果你要使用这个模型:

public class SurveyAnswer
{
public int SurveyId { get; set; }
public int question_1 { get; set; }
}

你可以像这样将它发送到 MVC 操作

[HttpPost]
public JsonResult Save(SurveyAnswer Survey)
{
// do work
return new JsonResult { Data = new { Success = true } };
}

这并没有回答你的第二个问题,但我希望它仍然对你有所帮助。

关于c# - MVC 中的动态表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13628161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com