Reputation: 11
My current url is /Product/Create?date=5/7/2014%2012:00:00%20AM
Actually I want like this: /Product/Create
My sample code is :
public class ProductController : Controller
{
public ActionResult Create(DateTime date)
{
ViewBag.Date = date;
return View();
}
}
Any one can help me?
Upvotes: 1
Views: 7058
Reputation: 11
In JS:
window.history.pushState("", "", "/Product/Create");
Upvotes: 1
Reputation: 23093
You can use HttpPost
to force this:
public class ProductController : Controller
{
[HttpPost]
public ActionResult Create(DateTime date)
{
ViewBag.Date = date;
return View();
}
}
And when calling the action you need to submit it via a form-post. If you show us the code how you call it we can help you there...
The HttpPost
attribut will force you to use "post" - if you still want the "other option" possible you can leave the attribute away and just use "post" for your desired case.
UPDATE:
You need to call the action like:
@using(Html.BeginForm("Create", "Product", FormMethod.Post))
{
@Html.Hidden("date", DateTime.Now.ToString())
<input type="submit" value="create">
}
To your current code <a href="/Product/[email protected]">
:
This creates a GET request and even if you want that you should do it like the following:
@Html.ActionLink("Create", "Product", new { date = DateTime.Now.ToString() })
This will take the proper routing in account and create a valid link.
Using e.g. JQuery
you can do the follwoing to have a link if JS is enabled:
@using(Html.BeginForm("Create", "Product", FormMethod.Post, new { id = "myForm" }))
{
@Html.Hidden("date", DateTime.Now.ToString())
<input id="myFormSubmit" type="submit" value="create">
<a id="myFormLink" href="#" style="display: none;" onclick="$('#myForm').submit(); return false;">create</a>
}
<script type="text/javascript">
$(document).ready(function () {
$('#myFormLink').show();
$('#myFormSubmit').hide();
});
<script>
Upvotes: 2
Reputation: 82096
Assuming that this is infact a GET request for a view which requires a Date
parameter (for whatever reason) I'd say your best bet is to pass the information as a custom header in the request
GET /Products/Create HTTP/1.1
X-YourApp-Date: 2014-07-05T12:00:00
Your action would then look like
public ActionResult Create() <-- no parameters
{
ViewBag.Date = DateTime.ParseExact(Request.Headers["X-YourApp-Date"],
"yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
return View();
}
Some side notes
Upvotes: 2
Reputation: 22054
In addition with controller change to handle only POST requests
...
[HttpPost]
public ActionResult Create(DateTime date)
...
You also have to change code for calling action in markup from link to something like
@using(Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { style = "display:inline" })) {
@Html.Hidden("date", DateTime.Now.ToString())
<a href="#" onclick="this.parentNode.submit(); return false">Whatever</a>
}
Upvotes: 1