我想将@survey
class Survey
的对象传递给JavaScript函数SubmitClick
,然后传递给SubmitSurvey
中的PersonController.cs
我的按钮:点击后,它会将参数传递给javascript:SubmitClick
<button class='mybutton' type='button' onclick="javascript:SubmitClick(@Model.Item1.Id, @survey);">Save Survey</button>
和JavaScript函数:
function SubmitClick(pid, sid) {
var url = '@Url.Action("SubmitSurvey", "Person")';
$.post(url, { personId: pid, survey: sid }, function (data) {
alert('updated' + pid);
});
}
以及我希望传递@survey
的方法:
public void SubmitSurvey(int personId, Survey survey) {
}
结果是:
我想指出传递@survey.Id
(int)是有效的,所以唯一的问题就是传递@survey
。
在将参数传递给java脚本函数时弹出错误。
修改
按钮位于foreach循环内,模型有点复杂。我可以在循环中将其序列化吗?
我将调查清单传递到此处的视图:
public ActionResult _Survey1(int id) {
System.Diagnostics.Debug.WriteLine("PASSED ID: " + id);
Person person = db.Persons.Find(id);
//Passing a Tuple to Partial View, I want to pass copies further I use copying constructor
List<Survey> localSurveysCopy = new List<Survey>();
foreach (Survey survey in db.Surveys) {
localSurveysCopy.Add(new Survey(survey));
}
var tuple = new Tuple<Person, List<Survey>>(person, localSurveysCopy) { };
return PartialView(tuple);
}
观点:
@using WebApplication2.Models
@model System.Tuple<Person, List<Survey>>
<hr />
<h1>Surveys</h1>
<input type="button" id="Coll" value="Collapse" onclick="javascript:CollapseDiv()" />
@{int i = 1;}
@foreach (var survey in Model.Item2) {
using (Html.BeginForm()) {
<h2>Survey @(i)</h2>
<p />
@Html.EditorFor(x => survey.Questions)
<button class='mybutton' type='button' onclick="javascript:SubmitClick(@Model.Item1.Id, @Newtonsoft.Json.JsonConvert.SerializeObject(survey));">Save Survey</button>
}
i++;
<hr style="background-color:rgb(126, 126, 126);height: 5px" />
}
<hr />
脚本。我想我必须直接传递变量,因为我有很多调查和许多按钮:
function SubmitClick(pid, sid) {
var url = '@Url.Action("SubmitSurvey", "Person")';
var objSurvey = $.parseJSON(sid);
$.post(url, { personId: pid, survey: objSurvey }, function (data) {
alert('updated person' + pid + ' survey ' + sid);
});
}
我明白了:
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in System.Web.Mvc.dll
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in System.Web.Mvc.dll
课程调查如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication2.Models {
public class Survey {
public int Id { set; get; }
public virtual ICollection<Question> Questions { set; get; }
public Survey() { }
public Survey(Survey survey) {
Id = survey.Id;
Questions = new List<Question>();
System.Diagnostics.Debug.WriteLine("SURVEY " + survey.Questions == null);
foreach (Question question in survey.Questions) {
Questions.Add(new Question(question));
}
}
}
public class Question {
public int Id { set; get; }
public string QuestionText { set; get; }
public virtual ICollection<Answer> Answers { set; get; }
public virtual Survey Survey { get; set; }
public string SelectedAnswer { set; get; } //this field is SET after clicking SAVE button
public Question() { }
public Question(Question question) {
Id = question.Id;
QuestionText = question.QuestionText;
Answers = question.Answers;
Survey = question.Survey;
SelectedAnswer = "";
}
}
public class Answer {
public int Id { set; get; }
public string AnswerText { set; get; }
public virtual Question Question { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
}
答案 0 :(得分:1)
你不能只将C#对象传递给JS并将其发回。
你应该:
<强>控制器:强>
string json = JsonConvert.SerializeObject(survey);
<强>标记:强>
<button class='mybutton' type='button' onclick="javascript:SubmitClick(@Model.Item1.Id, @json);">Save Survey</button>
<强>标记:强>
function SubmitClick(pid, sid) {
var objSurvey = $.parseJSON(sid);
var url = '@Url.Action("SubmitSurvey", "Person")';
$.post(url, { personId: pid, survey: objSurvey }, function (data) {
alert('updated' + pid);
});
}
<强>控制器:强>
public void SubmitSurvey(int personId, Survey survey) { }
<强>更新:强>
由于类之间的循环引用,无法正确序列化您的Survey实体。所以你在这里几乎没有选择:
答案 1 :(得分:1)
你做错了。
基本上当你@survey
时,你正在查看服务器端代码。在客户端,这个@survey
是一个强类型clr类的实例,它被转换为字符串,你知道当你将对象转换为字符串时会发生什么,你得到它的字符串类型,即
@survey.ToString() == "WebApplications2.Models.Survey"
显然这是错误的原因,最后,你的按钮标签的标记实际上变为:
<button class='mybutton' type='button'
onclick="javascript:SubmitClick(@Model.Item1.Id,
WebApplications2.Models.Survey);">
Save Survey
</button>
您基本上应首先在服务器端序列化@survey
对象并将其存储在隐藏变量中,即
@Html.Hidden("hdnSurvey", Newtonsoft.Json.JsonConvert.SerializeObject(Model))
并在javascript中使用此隐藏变量
即
function SubmitClick(pid) {
var objSurvey = $.parseJSON( $('#hdnSurvey').val());
var url = '@Url.Action("SubmitSurvey", "Person")';
$.post(url, { personId: pid, survey: objSurvey }, function (data) {
alert('updated' + pid);
});
}
答案 2 :(得分:0)
发送回@survey
变量毫无意义,来自UI的更改不会从变量中反映出来,但是从HTML输入中,您真正需要的是序列化表单。
以下是您真正需要的完整解决方案。
<强>模型强>
public class Person
{
public int Id { set; get; }
}
public class Survey
{
public int Id { set; get; }
public virtual ICollection<Question> Questions { set; get; }
}
public class Question
{
public int Id { set; get; }
public string QuestionText { set; get; }
public virtual ICollection<Answer> Answers { set; get; }
public int SelectedAnswerId { set; get; } // Notice that I change it into int not string
}
public class Answer
{
public int Id { set; get; }
public string AnswerText { set; get; }
}
<强>控制器强>
public ActionResult Index()
{
var person = new Person { Id = 1 };
var survey = new Survey
{
Id = 12,
Questions = new List<Question>
{
new Question
{
Id = 34,
QuestionText = "What is your favorite language?",
Answers = new List<Answer>
{
new Answer { Id = 56, AnswerText = "A#" },
new Answer { Id = 57, AnswerText = "B#" },
new Answer { Id = 58, AnswerText = "C#" }
}
}
}
};
var model = new Tuple<Person, List<Survey>>(person, new List<Survey> { survey });
return View(model);
}
[HttpPost]
public ActionResult SubmitSurvey(int personId, Survey survey)
{
return Json(new { success = true });
}
<强> Index.cshtml 强>
@model Tuple<Person, List<Survey>>
@{
ViewBag.Title = "Index";
}
<h2>Surveys</h2>
@{int i = 1;}
@foreach (var survey in Model.Item2)
{
using (Html.BeginForm())
{
<h3>Survey @(i++)</h3>
@Html.HiddenFor(x => survey.Id)
@Html.EditorFor(x => survey.Questions)
<button class="mybutton" type="button">Save Survey</button>
}
}
@section Scripts
{
<script>
$(".mybutton").click(function () {
var personId = "@Model.Item1.Id";
var survey = $(this).closest("form").serialize();
var data = survey + "&personId=" + personId;
$.ajax({
type: "POST",
url: "@Url.Action("SubmitSurvey", "Survey")",
data: data,
traditional: true,
success: function (data) {
alert("submitted :" + data.success);
}
});
});
</script>
}
<强> EditorTemplates / Question.cshtml 强>
@model Question
<h3>@Model.QuestionText </h3>
@Html.HiddenFor(x => x.Id)
@foreach (var a in Model.Answers)
{
<label>@Html.RadioButtonFor(b => b.SelectedAnswerId, a.Id) @a.AnswerText</label>
}
<强>结果强>
如果用户在第一个问题的第一次调查中选择了B#
,则提交的调查将返回SelectedAnswerId
为57.其他属性如Answers
和QuestionText
为null,它们对于保存并不重要,所以就这样吧。