MVC 4 Form submission doesn't result in desired url parameters - c#

I'm trying to use a form to allow the user to pick a date and pass it back to the controller by way of url parameters. My intention is to have the form submit a url that looks like Payroll/Index/id?employeeID="foo"?DayInWeekInput="bar". Instead this generates the url Payroll/Index/id? so I'm obviously doing something wrong. How can I do this with a form? If it's not possible, could you explain an alternative? Thanks.
using (Html.BeginForm("Index", "Payroll", new { id = #ViewBag.SupervisorID, employeeID=#ViewBag.EmployeeID }, FormMethod.Get))
{
#*#Html.AntiForgeryToken()*#
#Html.ValidationSummary(true)
<div class="editor-field">
<input type="date" id="DayInWeekInput" value="#string.Format("{0:yyyy-MM-dd}", Model.SpecifiedWeekStart)" />
<input type="submit" value="Go" />
</div>
}

you stopped naming, if you keep the names up it should work for you
using (Html.BeginForm("Index", "Payroll", new { id = #ViewBag.SupervisorID, EmployeeID = #ViewBag.EmployeeID, DaysInWeekInput = "bar" }, FormMethod.Get))
Since that didn't work for you I would try an ajax call next
$('.btnSubmit').on('click', function(){
$.ajax({
url: '#Url.Action( "Index", "Payroll" )',
data: {
id: #ViewBag.SupervisorID,
EmployeeID: #ViewBag.EmployeeID
},
success: function (_result) {
if (_result.Success) {
}
}
});
});
I would also recommend putting your id's in hidden fields. Viewbag can be unstable.

Related

Change view using ajax on drop-down list change event

I need to change the view in same page using ajax when the user changes the option of the drop-down list.
Up until now in my view I have the drop down list
<div class="wrapper">
<div>
<label>Get cars per people </label>
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
</div>
<div class="box box-success">
<div class="box-body">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</div>
</div>
Then in a script (which I found from another question)
$(document).ready(function () {
$("#ddlChangeID").change(function () {
var strSelected = "";
$("#ddlChangeID:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "/Cars/Index/" + strSelected;
$.post(url, function (data) {
});
});
})
And in the controller I am using ViewBag values to save the drop-down list values and whatever else is needed for the graph which loads in a different script again with ViewBag values. I have managed to pass the selected value (strSelected) but the view does not reload with the new data.
How should I make the ajax event?
Change your script ajax call by calling an action result as follows
$("#ddlChangeID").change(function () {
$.ajax({
url: "/Controller/ActionHtml?id="+$('#ddlChange').val(),
type: "POST",
cache: false,
success: function (result) {
$("#myChart").html(result);
},
error: function () {
$("#myChart").empty();
}
});
});
and in the controller the actionresult will be like the following which returns the html partial view that you need to append
public ActionResult ActionHtml(string id)
{
//Here you can load the data based on the id,pass model to the patial views etc
ViewBag.id = id;
return PartialView("~/Views/Shared/myhtml.cshtml");
}
myhtml.cshtml will be a partial view with the html content as
//content is dummy,change the content as you want
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
</form>
So I changed the
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
To
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #onchange = "ChangeOption()" })
adding also an id to the main div.
And the script to
function ChangeOption() {
var id = $('#ddlChange').val();
$.ajax({
url: '/Cars/Index',
type: "GET",
data: { Id: id },
success: function (data) {
$('#wrapAll').html(data);
}
});
}
It seems to work. Only issue now is that the css breaks.
It pushes the graph and drop-down list to the right breaking
the functionality.

How do I call my method in html?

I want to call my method in my mvc view. I have a method called SavePersoon wich has to save the changed data into my database. This is my code from my services:
public bool SavePersoon(PersoonModel persoon)
{
bool result = true;
db.Persoon.AddOrUpdate(persoon.GetPoco());
db.SaveChanges();
return result;
}
This is the button who has to be pressed and then this code above has to deal the work itself.
The view:
<button type="button" id="btnSaveChanges" class="btn btn-primary">Opslaan</button>
Do I have to use something similair like <asp:LinkButton...?
You can make use of Ajax , Something like this
$("#btnSaveChanges").on("click",function(){
$.ajax({
url:"/controllerName/SavePersoon",
data:$("#formName").serialize(),
cache:false,
type:"POST",
error:function(){
alert("Error");
}
});
});
If you use Razor view engaine, you can make your method return an action result and call it from the view using Html.Actionlink.
You can do 2 things:
Use the HTML Helpers that ASP.Net MVC provides to create a form which posts to the required method, something like 'Save' of the controller 'Person':
#using (Html.BeginForm("Save", "Person", FormMethod.Post, new { #class = "form-horizontal" })) {
<div>
<!-- Your HTML, this could for example be a text field for the person its name -->
#Html.TextBoxFor(Model => Model.Name, new { #class = "form-control" })
<input type="submit" class="btn btn-primary" value="Save" />
</div>
}
This will create a form tag for you, something like <form action="person/save" method="post"> ... your HTML & the submit button ... </form>
An alternative is to use Ajax to prevent the page from refreshing as stated in the above post.
$("#btnSaveChanges").on("click",function(){
$.ajax({
url: '#Url.Action("Save", "Person")', // Again an MVC HTML Helper to create a URL
data:$("#Name").val(), // Posts the value of a text field with ID "Name"
cache:false,
type:"POST",
success: funcion(returnValue) {
// Do something with the result.
}
error:function(){
alert("Error");
}
});
});

Ajax Form Begin is not going to http GET method

I am trying to send the text box values in ajax form begin and show the corresponding partial view But the problem is it always going to the post method but i mension the httpmethod also in ajax form
My Code is
#using (Ajax.BeginForm("UserMenuPermission", new AjaxOptions { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "GridData" }))
{
<div>
#Html.Label("User Name")
<input type="text" placeholder="User Name" style="color: black;height:30px;" name="Username"/>
<input type="submit" value="Search" />
</div>
}
This code can pass the information to UserMenuPermissionController POST method but i need to pass in GET Method Please Help Me Friends
Thanks In Advance.
I Suggest that use jquery.ajax get method
//Change your search button like this
<input type="button" value="Search" onclick="ajaxCall()" />
//in javascript
function ajaxCall()
{
$.ajax({
url: "ActionURL",
type:"get", //send it through get method
data:{}
success: function(response) {
//response is your partialview html
},
error: function(xhr) {
//Do Something to handle error
}
});
}
in controller
public ActionResult GetHtml( )
{
return PartialView( "UserDetails");
}

MVC Delete not hitting HttpPost Method

I'm using MVC3. I learned that its a bad practice to delete an item using HttpGet Method as any one can browse to the url and deletes an item. So I want to perform delete operation on HttpPost Method.
The problem is that when I click delete button, it gets hit on HttpGet method only but not on HttpPost method.
I've used webgrid and its the index.cshtml file
<div id="DataTable">
#grid.GetHtml(htmlAttributes: new {id="gvMovies" },
columns:grid.Columns(
grid.Column("Title","Movie Title",canSort:true),
grid.Column("Director","Film Maker",canSort:false),
grid.Column(header:"Action",
format:#<text>
Edit
#using (Html.BeginForm("Delete", "Movies", new { id = #item.id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ActionLink("Delete", "Delete", new { id = #item.id }, new { onclick = "return confirm('Are you sure you wish to delete this article?');" })
}
</text>)))
</div>
The controller page is as follows
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id)
{
return RedirectToAction("Index");
}
Conceptually it's not correct to use the POST verb for delete. POST - is intended for posting information. The correct way would be to to just remove the attribute from the Delete method, and let it go with the GET verb.
Now if you really really really need to use the POST, your first mistake is that you create a link, instead of a submit button that will submit the form. Replace
#Html.ActionLink("Delete", "De...
with:
<input type="submit" value="Delete">
you must add submit button instead of link so you must change
#Html.ActionLink("Delete" to <input type=submit value="del" >
if you want send id in the post you can add hidden input in the form so you can add some thing like this before your submit button in the form
<input type="hidden" value=#item.Id name="itemid" >
so i think this code will work
#using (Html.BeginForm("Delete", "Movies", new { id = #item.id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="hidden" value=#item.Id name="itemid" >
<input type=submit value="del" >
}

How to add additional data in my JQUERY submit?

In my razor view, I'm using a Html.BeginForm. In it I have two elements where when I set clic, should submit the form but I need to add an additional string parameter.
#using (Html.BeginForm("Index", "Quiz", FormMethod.Post, new { id = "form" }))
{
...
}
[HttpPost]
public ActionResult Index(string parameter, QuizCompletedViewModel q) //FormCollection f)
{
...
if (button.Equals("d"))
{
...
return RedirectToAction("ShowResults", new { testId = Quiz.QuizId, answeredTest = answeredId });
}
else
{
...
return RedirectToAction("Index", "Dashboard");
}
}
So, in my jquery function I utilize $("#element").submit() and the parameter parameter always is null (and that's normal). How can I add additional data for parameter using JQUERY?
NOTE: I'm not using AJAX.
On your form sumbit try like this:
$("form").submit(function(){
$.ajax({
type: 'POST',
url: "/Quiz/Index",
dataType: "json",
data: $("form").serialize() + '&parameter=param1' ,
success: function () {
alert("Successful");
}
error: function(){
alert('error');
}
});
});
Hope it helps.
Edit
Try like this in your jQuery function:
$('form').append('&param=a');
You could add a hidden input with the name and value you require in your form. This value will be submitted along with all the other form items.
<input type="hidden" name="someName" value="someValue" />
Edit for comment:
If you give each of your submit buttons the value as an attribute you could grab it in the click handler and then append a hidden field with the value inside the form. Something like:
$(function(){
$('#form input[type=submit]').click(function(e) {
var val = this.getAttribute("data-param");
$(this).closest('form').append('<input type="hidden" name="param" value="' + val + '" />");
});
});
Untested, just a hunch. Hope that the form submit event does not get fired before the button click event. Also you will need to handle the enter event and key press etc.
Why don't you want to use ajax?
Based on your comments, the easiest thing for you to do is make your buttons of type submit and give them a name. If they have a name, the value of the button that is clicked will be sent automatically with the form post, see: sending form's submit button's value?
Example:
When the a button is clicked, parameter will be posted with value a. Likewise for b and c. If the none button is clicked, no value will be sent and parameter will be null (shown for demonstration purposes, you may not need this).
#using (Html.BeginForm("Index", "Quiz", FormMethod.Post, new { id = "form" }))
{
...
<input type="submit" value="a" name="parameter" />
<input type="submit" value="b" name="parameter" />
<input type="submit" value="c" name="parameter" />
<input type="submit" value="none" />
}

Categories