Reputation: 884
I am very new to MVC and I am trying to get the date the user selects from the date picker and display another set of dates based on a user input. The date picker works fine however I am not sure how to get the value of the date and pass it to the calculation. I have created a textbox to get the number of days the user wants displayed and the button to initiate the calculation, however the way I created the button also created another text box.
Here is the view code:
@using (Html.BeginForm())
{
<h2>Enter The Number Of Days To Display</h2>
Date: <input type="text" id="date" name="date"value ="Enter a number"/>
@Html.TextBoxFor(model => model.DaysToBeViewed)
<input type="submit" value="Display Days" />
Upvotes: 1
Views: 2127
Reputation: 1685
You can partially post the date value to the controller method. Like this:
@using (Html.BeginForm()) {
Javascript:
$(document).ready(function(){
$("#submitDate").on("click", function(){
$.ajax({
type: "POST",
url: "../MyController/Calculate?date=" + $("input#date").val(),
// syntax was wrong here
success: function (result) {
$("#DaysToBeViewed").val(result);
},
error: function () {
alert("Error in calculation method");
}
});
});
});
Controller:
public string Calculate(string date)
{
// do your calculation here
return date;
}
View:
@using (Html.BeginForm("Calculate", "ControllerName", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<h2>Enter The Number Of Days To Display</h2>
Date: <input type="text" id="date" name="date" value ="Enter a number"/>
@Html.TextBoxFor(model => model.DaysToBeViewed)
<input type="submit" value="Display Days" />
}
Model:
public class MyData
{
public string DaysToBeViewed {get; set;}
public string date {get; set;}
}
Controller:
[HttpPost]
public ActionResult Calculate(MyData myData)
{
// do your calculation here
return View();
}
Upvotes: 2