Currently I have a javascript function for a button inside a Razor view where when user clicked it, a popup message will appear.
$("#confirmBtn").click(function() {
alert("user confirmed address: " + address + street + country);
Now I want to change the function so that when user clicked on it, it will send the parameter to the controller "SaveAddress" as HttpPost.
How can I achieve this? Thanks.
use ajax form in MVC
@using (Ajax.BeginForm("SaveAddress", "YourController", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "elementwhichholdsthisform", OnSuccess = "OnFilterSuccess" }, new { id = "frmSaveAddress" }))
{
}
Also remember to add reference to
jquery.unobtrusive-ajax.js
Create a dto class:
public class AddressDto
{
public string Address { get; set; }
public string Street { get; set; }
public string Country { get; set; }
}
Your controller method:
public ActionResult SaveData(AddressDto dto)
{
// do stuff
return Json(true);
}
Your ajax request:
$("#confirmBtn").click(function() {
// get values and pass them to dto
var dto = {
Address: address,
Street: street,
Country: country
};
$.ajax({
url: 'MyController/SaveData',
type: 'POST',
data: { dto: dto },
success: function (result) {
// do stuff
}
});
}
You have 2 options either using Form Postback or by using AJAX
--by Using ajax like below
-- View Section
<input type="text" id="address" name="address"/>
<input type="submit" id="btnSubmit" Value="Submit"
onclick="return myFunction()" />
-- Script Section
<script type="text/javascript">
var address=$('#address').val();
function myFunction(shipId) {
$.ajax({
type: 'POST',
url: '@Url.Content("~/YourControllerName/SaveAddress")',
cache: false,
data: ({ add: address}),
success: function (data) {
if (data != null) {
alert("Operation Completed")
}
},
error: function () {
}
});
return false;
}
</script>
--Controller
public ActionResult SaveAddress(string add)
{
//Write your code here
return Json("", JsonRequestBehavior.AllowGet);
}
Note:- You can create your model class and able to send multiple value's as for demo i am just sending single value.
--by Using Form Post like below
--Model Class
public class MyClass
{
public string address {get;set;}
public string street {get;set;}
}
-- Controller
[HttpGet]
public ActionResult SaveAddress()
{
//Write your code here
return View();
}
[HttpPost]
public ActionResult SaveAddress(MyClass myclass)
{
//Write your code here
return RedirectToAction();
}
-- View
@model YourSolutionName.Models.MyClass
@using (Html.BeginForm("SaveAddress","Your Controller Name",FormMethod.Post))
{
@Html.TextBoxFor(x => x.address )<br/>
@Html.TextBoxFor(x => x.street)
<br/>
<input type="submit" id="btnSubmit" Value="Submit" />
}
I hope it may help you. Thank You
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.