在Javascript中设置值会导致控制器-MVC

时间:2018-10-24 09:29:24

标签: javascript c# model-view-controller kendo-asp.net-mvc kendo-listview

我对MVC(以及一般而言的Web开发)还很陌生,并且我不断遇到一些“陷阱”,这会导致意外的行为。我正在使用Kendo UI,但是我99%确信我的问题是由于我对Javascript或MVC缺乏了解,而不是与Kendo无关。

您应该可以使用以下代码重现该问题:

型号:

public class DemoClass
{
    public int id { get; set; }
    public string randomData { get; set; }

    public List<DemoPartyDetails> partyDetails { get; set; }

    public DemoClass()
    {
        partyDetails = new List<DemoPartyDetails>();
    }
}

public class DemoPartyDetails
{
    public int id { get; set; }
    public string firstName { get; set; }
    public string surname { get; set; }

    public string gender { get; set; }

    public DemoPartyDetails()
    {

    }
}

控制器:

public class DemoController : Controller
{
    // GET: Demo
    public ActionResult Index()
    {
        DemoClass demo = new DemoClass();
        return View(demo);
    }

    [HttpPost]
    public ActionResult Create(DemoClass model)
    {
        try
        {
            if (model.partyDetails[0].gender != null)
                Console.WriteLine("Party details populated");
            else
                Console.WriteLine("Something went wrong...");

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}

查看:

@model DemoPortal.Models.DemoClass

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    @using (Html.BeginForm("Create", "Demo", FormMethod.Post))
    {
        <div>
            @Html.EditorFor(model => model.randomData)
        </div>

        <div>
            <a class="k-button k-button-icontext k-add-button" href="#"><span class="k-icon k-i-add"></span>Add Party</a>
            @(Html.Kendo().ListView(Model.partyDetails)
                    .Name("demoListView")
                    .TagName("div")
                    .ClientTemplateId("demoTemplate")
                    .DataSource(dataSource => dataSource
                        .Model(model => model.Id(x => x.id))
                        )
                    .Editable(editable => editable.TemplateName("DemoPartyDetails"))
            )
        </div>

        <input type="submit" value="Submit" />
    }
</body>
</html>


<script type="text/x-kendo-tmpl" id="demoTemplate">
    <div class="demoParty">
        <h3>#:firstName#</h3>
        <span>#:surname#</span>

        <input type="hidden" name="PartyDetails[#:index(data)#].firstName" value="#:firstName#" />
        <input type="hidden" name="PartyDetails[#:index(data)#].surname" value="#:surname#" />
        <input type="hidden" name="PartyDetails[#:index(data)#].gender" value="#:gender#" />
    </div>
</script>


<script>
$(function() {
        var listView = $("#demoListView").data("kendoListView");

        $(".k-add-button").click(function(e) {
            listView.add();
            e.preventDefault();
        });
});

function index(dataItem) {
    var data = $("#demoListView").data("kendoListView").dataSource.data();

    return data.indexOf(dataItem);

}

function maleClick(e) {
    document.getElementById("gender").value = "M";
    document.getElementById("randomData").value = "random";

    var maleButton = document.getElementById("IsMale");
    var femaleButton = document.getElementById("IsFemale");
    femaleButton.classList.remove("k-primary");
    maleButton.classList.add("k-primary");
};

function femaleClick(e) {
    document.getElementById("gender").value = "F";
    document.getElementById("randomData").value = "random";

    var maleButton = document.getElementById("IsMale");
    var femaleButton = document.getElementById("IsFemale");
    maleButton.classList.remove("k-primary");
    femaleButton.classList.add("k-primary");
};
</script>

PartyDetails编辑器模板

@model DemoPortal.Models.DemoPartyDetails

@using (Html.BeginForm())
{
    <div>
        <div>
            <label>Gender:</label>
            @(Html.Kendo().Button()
                    .Name("IsMale")
                    .Content("Male")
                    .HtmlAttributes(new { type = "button" })
                    .Events(ev => ev.Click("maleClick")))

            @(Html.Kendo().Button()
                    .Name("IsFemale")
                    .Content("Female")
                    .HtmlAttributes(new { type = "button", @class = "k-primary" })
                    .Events(ev => ev.Click("femaleClick")))
        </div>

        @(Html.HiddenFor(model => model.id))
        @(Html.EditorFor(model => model.gender))
        @(Html.EditorFor(model => model.firstName))
        @(Html.EditorFor(model => model.surname))

        <div class="btnArea">
            <a class="k-button k-update-button" href="\\#"><span class="k-icon k-update"></span></a>
            <a class="k-button k-cancel-button" href="\\#"><span class="k-icon k-cancel"></span></a>
        </div>
    </div>

}

运行此代码时,我可以单击按钮添加一个新的聚会,编辑器模板将按预期显示,然后按“男性”按钮,该按钮将在性别字段中填充“ M”。

然后在确认输入然后按Submit之前,使用通用的“ Test”和“ Person”数据填写其他两个字段。

但是,当我在控制器上放置一个断点时,我发现通过的模型的性别设置为null。但是,姓和名(“测试”和“人”)已完全填充。也按预期填充了randomData。

有趣的是,如果我返回并在“性别”字段中手动键入类似“男性”的内容,那么现在也已填充该字段。仅当我尝试使用javascript设置其值为null时。

最终目的是要在按下按钮时用javascript填充一个隐藏字段,因此如果有人指出我的错误,将不胜感激!

1 个答案:

答案 0 :(得分:0)

原来,您需要通过javascript更改值后触发编辑器模板的change事件。

   <select name="trip" class="select-trip">
  <?php foreach ( $wp_trips as $trip ) {
    if ($trip->available && $is_day_trip){
         $start = date_i18n("d/m/Y", strtotime($trip->start_date));
         $end = date_i18n("d/m/Y", strtotime($trip->end_date));?>
        <option value="<?php echo $trip->remote_ID; ?>">
        <?php echo $start;
      } else {
          echo $start . ' T/M ' . $end;
      }
    } ?>
  </select>