Asp.net MVC与实体,使用jQuery将数据传递到列表中。不工作 [英] Asp.net MVC with Entity, using jquery to pass data into List. Does not work

查看:132
本文介绍了Asp.net MVC与实体,使用jQuery将数据传递到列表中。不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改3 /决赛

这是使用.NET MVC,jQuery和编辑模板完全工作的例子。
https://www.dropbox.com/s/t4yxbhkuowyd7va/exerciseTest.rar

This is the fully working example using .NET MVC, Jquery and editor templates. https://www.dropbox.com/s/t4yxbhkuowyd7va/exerciseTest.rar

编辑2

最后,它的工作原理!由于下面的答案。看来,我需要改变NewAnswerRow偏行:

It finally works ! Thanks to the answer below. It appears that i needed to change the NewAnswerRow partial line:

<input type='text' id='Answers_@(Model.AnswerId)__Answer'   name='Answers[@Model.AnswerId].Answer'/>

谢谢!

编辑1:

我已经按照本指南:
http://www.techiesweb.net/asp-net-mvc3-dynamically-added-form-fields-model-binding/

有趣的是,当我使用他的源代码,它的工作原理像它应该。但它几乎是完全一样的。

The funny part is, that when I use his source, it works like it should. But it is almost exactly the same.

原贴

首先感谢所有阅读这条消息,并愿意提供帮助。我大吃一惊。让我试着解释我的处境。我试图创建一个与答案列表,一个新的练习。这些答案都在使用jQuery动态创建。我在读与EditorTemplates这些问题的答案。一切正常,只是当我创造新的答案字段和preSS'邮'我的控制器不能看到任何数据(答案)。奇怪的是。当我使用像[要求]在例如一个答案的属性数据注解。我越来越重定向到指数。当我再次尝试它,我的模型是不是空了。

First off all thanks for reading this message, and willing to help. I'm flabbergasted. Let me try to explain my situation. I'm trying to create a new exercise which has a list with answers. These answers are created on the fly with Jquery. I'm reading those answers with EditorTemplates. Everything works except that when i create new 'Answer' fields and press 'Post' My controller cant see any data (answers). The weird thing is. When I use data annotations like [required] in for example an answer property. I'm getting redirected to the Index. When I try it again, my model isn't empty anymore.

所以基本上我的问题是,我怎么能设法让这些答案进入我的列表?

So basically my question is, how can i manage to get those answers into my list?

我创建了一个新的项目为你们更加明确和具体。

I've created a new project for you guys to be more clear and specific.

我有2个型号,


  • 运动

  • Exercise

答案

ExerciseModel类

[Table("Exercise")]
public class ExerciseModel
{

    [Key]
    public int ExerciseId { get; set; }


    public string Question { get; set; }


    public IList<AnswerModel> Answers { get; set; }
}

这基本上是一个简单的类。正如你们所看到。有有答案的列表。

It's basically a simple class. As you guys can see. There's a List with Answers.

AnswerModel

[Table("Answer")]
public class AnswerModel
{
    [Key]
    public int AnswerId { get; set; }

    public string Answer { get; set; }
 }

一个简单的AnswerModel类ID和一个答案。

A simple AnswerModel class with an Id and an Answer.

我的控制器

public class ExerciseController : Controller
{
    private readonly DataContext db = new DataContext();
    //
    // GET: /Exercise/
    public ActionResult Index()
    {
        var exercise = new ExerciseModel();
        exercise.Answers = GetAnswers();

        return View(exercise);
    }


    [HttpPost]
    public ActionResult Index(ExerciseModel exercisemodel)
    {
        //need to implement interaction with database (not yet) testing phase.
        return View("PostedData", exercisemodel);
    }


    public ActionResult NewAnswersRow(int id)
    {
        var answers = new AnswerModel { AnswerId = id };
        return View("partial/NewAnswersRow", answers);
    }


    private List<AnswerModel> GetAnswers()
    {
        var answerslist = new List<AnswerModel>();
        answerslist.Add(new AnswerModel { AnswerId = 1, Answer = "This is a hardcoded answer"}); //normally db.Answers (for testing purposes)
        return answerslist;
    }

}

我的索引视图

@model exerciseTest.Models.ExerciseModel
@using (Html.BeginForm())
{

    <div class="divAnswers">
        <div  id="container">
            <div class="editor-label">
                @Html.LabelFor(model => model.Question)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Question)
                @Html.ValidationMessageFor(model => model.Question)
            </div>
            @Html.EditorFor(m => m.Answers)

        </div>
        <input type="button" id="btnAdd" value="Add New Item" />
    </div>
    <p>
        <input type="submit" value="Save" />
    </p>
}


    <script>

$(function () {
    $("#btnAdd").click(function (e) {
        var itemIndex = $("#container input.iHidden").length;
        console.debug("itemIndex : "+itemIndex);
        e.preventDefault();
        $.get("@Url.Action("NewAnswersRow", "Exercise")/"+itemIndex,function(data){
            $("#container").append(data);
        });           
    });
});

</script>

我的编辑AnswerModel模板

@model exerciseTest.Models.AnswerModel
@{
    Layout = null;
}
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<tr> 
 <td>
  @Html.HiddenFor(x => x.AnswerId, new { @class="iHidden" })
 @Html.TextBoxFor(x => x.Answer) </td>
</tr>

我的NewAnswersRow.cshtml上使用jQuery动态创建新行(见指数为code部分)

@model exerciseTest.Models.AnswerModel
@{    Layout = null; }
<tr> 
 <td>
  <input type="hidden" id="Answers_@(Model.AnswerId)__Id" class="iHidden"  name='Answers[@Model.AnswerId].Id' />
  <input type='text' id='Answers_@(Model.AnswerId)__AnswersText'   name='Answers[@Model.AnswerId].AnswersText'/>
 </td>
</tr>

并用于测试目的我的'postedData视图

@model exerciseTest.Models.ExerciseModel
<h3>Posted data is </h3>

@foreach (var item in Model.Answers)
{
   <p>@item.Answer</p>
}

我试图让这件事的工作。我必须说,在像5年来,我从来没有问这里成才的StackOverflow因为我能找到答案。但是这一次,我需要你的帮助。

I'm trying to get this thing to work. I must say, In like 5 years, i've never asked someting here on StackOverflow because i could find answers. But this time, I need your help.

谢谢!

推荐答案

您在你的 NewAnswersRow局部视图中的错误名称编号是在你的HTML一样,但它是在窗体发布传递的名称。如果你看一下 MVC 在做什么,答案文本字段的名称属性是答案[X]。答 ,而编号答案[X] .AnswerText

You have a bug in your NewAnswersRow partial view. Name and Id are the same in your html, however it is name that is passed in a form post. If you look at what MVC is doing, the name attribute of the answer text field is Answers[x].Answer, while the Id is Answers[x].AnswerText.

因此​​,改变你的名称='答案[@ Model.AnswerId] .AnswerText 名称='答案[@ Model.AnswerId。回答所以它匹配什么 MVC 期待。为我工作!

So change your name='Answers[@Model.AnswerId].AnswerText' to name='Answers[@Model.AnswerId].Answer' so it matches what MVC is expecting. Worked for me!

这篇关于Asp.net MVC与实体,使用jQuery将数据传递到列表中。不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆