Display text when button clicked

独自空忆成欢 提交于 2020-01-05 08:13:29

问题


Creating my first ASP.NET MVC Knockout MVC.

I've added a model setting 3 dates. The controller assigns 3 dates. Then they are displayed on screen using the view:

<p>First Date: @ko.Html.TextBox(m => m.FirstDate)</p>
<p>Second Date: @ko.Html.TextBox(m => m.SecondDate)</p>
<p>Third Date: @ko.Html.TextBox(m => m.ThirdDate)</p>

@ko.Apply(Model)

The @ko.Apply(Model) being the main part which displays the 3 dates. I am trying to only show the 3 dates when a button is clicked, so iv put the code inside a form and used a button:

<form id="displaydates" method="post" >
<p>First Date: @ko.Html.TextBox(m => m.FirstDate)</p>
<p>Second Date: @ko.Html.TextBox(m => m.SecondDate)</p>
<p>Third Date: @ko.Html.TextBox(m => m.ThirdDate)</p>

<input id="btn" type="button" value="click" @ko.Apply(Model) />
</form>

Problem being this no longer displays the dates in the text box, they display them beside the button. To recpa: I would like each date to appear inside the text box when the button is clicked (instead of alongside the button when the page loads - which is what happens atm).

Any ideas?

Update Tried to add a button, but now the dates dont display at all, even when the button is clicked.

View:

@using PerpetuumSoft.Knockout
@model KnockOutMVC3Dates.Models.DatesModel       
@{
  var ko = Html.CreateKnockoutContext();
}

<p>First Date: @ko.Html.TextBox(m => m.FirstDate)</p>
<p>Second Date: @ko.Html.TextBox(m => m.SecondDate)</p>
<p>Third Date: @ko.Html.TextBox(m => m.ThirdDate)</p>

@ko.Html.Button("Display","Index","Dates",null,null)

Dates Controller:

   public ActionResult Index()
        {
            return View
                (   new DatesModel
                    {
                        FirstDate = DateTime.Now,

                        SecondDate = DateTime.Now.AddYears(1).AddMonths(1),
                        ThirdDate = DateTime.Now.AddYears(2).AddMonths(2)
                    }
                );

        }

Model:

  public class DatesModel
{
    public DateTime FirstDate { get; set; }
    public DateTime SecondDate { get; set; }
    public DateTime ThirdDate { get; set; }
}

Any help or ideas welcome??


回答1:


Maybe you want something like this?

<input id="btn" type="button" value="click" onclick="@(ko.Apply(Model))" />

I am not especially familiar with Knockout JS but it appears that the return value of ko.Apply(Model) is a bunch of JS to populate your fields. If you want to run this on click of your button, you'll want the above. Right now, you're writing out a load of JS into your input tag, which is just breaking.




回答2:


input tag can be used here like on the onclick event u can give the name of the model also try this...



来源:https://stackoverflow.com/questions/16083648/display-text-when-button-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!