How do I call my method in html? - c#

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");
}
});
});

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.

Bootstrap Modal pass input parameter to controller without closing modal

I have a Modal with 2 Tabs and I have an input on one of them. I need to pass the value of that input to the controller after clicking the search button. After that, the modal should stay. How can i pass the parameter to the controller without closing the modal?
<div class="modal-body">
#using (Html.BeginForm("SearchKuerzel", "Home"))
{
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="USZ-Kürzel" id="MyParameter" aria-label="USZ-Kürzel" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Mitarbeiter suchen</button>
</div>
</div>
}
</div>
You can either use javascript like #3xGuy has said or use jquery such as below:
$('#MyParameter').val();
to get the value and then use ajax to send information to the controller. From here can do whatever you want in the controller and just return Json such as below from the controller.
return Json(new {success = //true or false or whatever});
EDIT:
Once you have done what you want in the controller, you can return the value like I have returned the variable 'success' in the code above. In the result section of the ajax request you can get the data from the controller such as this:
//the rest of the ajax request
success: function(result)
{
//Change the value of html element to success in this case
$('#//id of the element').text(result.success)
}
EDIT 2:
To return two Json strings do as above but add another return such as:
return Json(new {string1 = //whatever, string2 = //whatever});
And in the ajax access them like:
success:function(result)
{
var return1= result.string1;
var return12 = result.string2;
}

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");
}

Show loading panel on index action of ASPNET MVC

In my ASP.NET MVC 5 web site i have a devexpress navbar with multiple itens, each item have a single unique controller, always when i click on a item the Index action of the corresponding controller is called.
public ActionResult Index()
{
//Load large data and return it into a gridview.
}
While im loading this data i would like to show a loading panel but i dont know where i can do it using in mvc, in aspnet webforms its easier to do something like that.
Any MVC expert could help me with this?
Inside your view you suppose to use am Ajax Form, and to point to your LoadingElementId in it's definition.
Here is an example:
#using (Ajax.BeginForm("FilterNews", "News", null,
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "container", LoadingElementId = "custom-loading" }))
{
<div id='container'>
//Your helpers #Html.TextBoxFor(x => x.....) or render a partial
</div>
}
<style>
.loading{
position:absolute;
width:100%,
height:100%,
top:0,
left:0,
background:white,
}
</style>
<div id="custom-loading" class="loading">Loading..Please wait...</div>
Also if you want to display a Loader for every XHR Call u may set a binder on ajaxSend event like this :
<div id="ajax-loader-element">
<img src="#Url.Content("~/Content/Images/ajax-loader.gif")"/>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(document).bind("ajaxSend", function () {
jQuery('#ajax-loader-element').show();
}).bind("ajaxComplete", function() {
jQuery('#ajax-loader-element').hide();
});
});
</script>

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

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.

Categories