I am trying to pass parameter from view to controller,
This is my View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#foreach (var pricedetails in ViewBag.PriceTotal)
{
<div style="text-align:center; clear:both ">
<h5 class="product-title">#pricedetails.Title</h5>
</div>
<div class="product-desciption" style="height:40px">#pricedetails.Descriptions</div>
<p class="product-desciption product-old-price"> #pricedetails.PricePoints</p>
<div class="product-meta">
<ul class="product-price-list">
<li>
<span class="product-price">#pricedetails.PricePoints</span>
</li>
<li>
<span class="product-save">Get This Free</span>
</li>
</ul>
<ul class="product-actions-list">
<input type="submit" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />
</ul>
</div>
}
}
my action method:
On submit it reaches the Action Method, but I am not able to get the PriceId for each Price
[HttpPost]
public ActionResult Index(int id=0) // here PriceId is not passed on submit
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Content("<script language='javascript' type='text/javascript'>alert('You are not elgible');</script>");
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('You are elgible');</script>");
}
return View("Index");
}
Url Routing:
routes.MapRoute(
name: "homeas",
url: "Index/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
May I know what wrong I am doing ?
Please use the following in your cshtml page
#foreach (var item in Model)
{
#Html.ActionLink(item.PriceDetails, "GetGift", new { priceID = item.priceID }, new { #class = "lnkGetGift" })
}
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a.lnkGetGift").on("click", function (event) {
event.preventDefault();
$.get($(this).attr("href"), function (isEligible) {
if (isEligible) {
alert('eligible messsage');
}
else
{
alert('not eligible messsage');
}
})
});
});
</script>
and in controller
[HttpGet]
public JsonResult GetGift(int priceID)
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
Please change your parameters according to the method param and price entity
Hope this helps.
I suggest you get rid of the Html.BeginForm(). Just leave the for...loop and define your "Get Gift" button like this:
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(pricedetails.PriceId))'" />
Then, at the bottom of the view file where the Get Gift button is located, define some JavaScript:
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("Index", "Home")',
data: { priceId: priceId },
contentType : "json",
success:function(data){
// Do whatever in the success.
},
error:function(){
// Do whatever in the error.
}
});
</script>
By using an ajax call to get the gift data, you don't have to submit anything. This makes things a lot easier in your case. Pressing the Get Gift button simply makes an ajax call.
I don't have time to try this out myself, but hopefully the above example should get you up and running.
EDIT:
I've managed to sneak in some time to come up with an example.
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var items = new List<int>();
items.Add(1);
items.Add(2);
items.Add(3);
return View(items);
}
public ActionResult GetGift(int priceId)
{
return RedirectToAction("Index"); // You'll be returning something else.
}
}
View
#model List<int>
#foreach (var price in Model)
{
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(price))" />
}
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("GetGift", "Home")',
data: { priceId: priceId },
contentType: "json",
success: function(data) {
// Do whatever in the success.
},
error: function() {
// Do whatever in the error.
}
});
}
</script>
Hope this helps you.
I think you should correct here
<input type="button" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />
Related
view:
#using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
{
foreach (var item in Model.QualityModel)
{
<li><input type="checkbox" name="qualitycheck"/><span>item.qualityName</span></li>
}
}
Controller:
public ActionResult Searchbyquality(string[] qualitycheck )
{
//code of searching
}
I want to pass multiple selected value to the controller
Your View Code Should be :
#using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
{
foreach (var item in Model.QualityModel)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="qualitycheck"
value="#item.qualityName" /> #item.qualityName
</label>
</div>
}
#*<div class="form-group text-center">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>*#
}
For without Submit button you have to add jQuery Code to call controller action :
$( document ).ready(function() {
$(":checkbox").change(function() {
if(this.checked) {
var qualitycheck_data = { 'qualitycheck': [] };
$('input:checked').each(function ()
{
if(this.name == 'qualitycheck') qualitycheck_data['qualitycheck'].push($(this).val());
});
var path = "/Health/Searchbyquality";
$.ajax({
url: path, type: "POST", cache: "false",
dataType: "json", contentType: "application/json; charset=utf-8",
data: JSON.stringify(qualitycheck_data),
traditional: true,
converters: {'text json': true}
}).success(function (responseText) {
//Success result
window.location.assign(responseText);
}).error(function (responseText){
swal("Error!", "Test 1", "error");
});
//swal("Error!", "Test 2", "error");
}
});
});
And your Controller Action :
[HttpPost]
public ActionResult Searchbyquality(string[] qualitycheck )
{
//code of searching
return View("");
}
cheers !!
I have html like this:
HTML
<div class="col-md-3 col-sm-12">
<div>
<p>Región</p>
<select id="lstRegion" class="form-control agenda_space" aria-hidden="true"></select>
</div>
<div>
<p>Solicitud</p>
<select id="lstSolicitud" class="form-control agenda_space" aria-hidden="true"> </select>
</div>
<br/>
<div>
Actualizar Filtro
<br/>
</div>
JS:
$("#lstRegion")
.getJSONCatalog({
onSuccess: function (response) {
console.log(response);
},
url: '/Agenda/GetRegion',
valueProperty: "ID",
textProperty: "valor"
});
//Load solicitud dropdown
$("#lstSolicitud")
.getJSONCatalog({
url: '/Agenda/GetSolicitud',
valueProperty: "ID",
textProperty: "solicitud"
});
Controller:
public ActionResult GetRegion()
{
try
{
var listaRegistros = db.CatalogoRegistros.Where(x => x.CatalogosCodigo == "REGI").Select(x => new
{
x.ID
,
valor = x.Valor
});
return Json(listaRegistros, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}
public ActionResult GetSolicitud()
{
try
{
var listasolicitud = db.Solicitudes.Select(x => new { x.ID, solicitud = "Folio: " + x.ID });
return Json(listasolicitud, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}
They work great I get my dropdwon lists very well, but now I want to do a GET action with selected values of each dropdown when my Actualizar Filtro it´s clicked.
But I´m really new in asp.net and I don´t know what I need to do to get selected values and send to controller.
As googling it I found I need to do method into my controller to get values so:
Controller will be:
public ActionResult GetTareas(string lstRegionValue, string lstsolicitudValue)
{
}
But I don´t know how to send them via JS, how can I do that to receive selected parameters into my controller? Regards
UPDATE
I try it using Ajax like:
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas")',
data: { region: $('#lstRegion option:selected').html(), solicitud: $('#lstSolicitud option:selected').html() }, // pass the value to the id parameter
dataType: 'json',
success: function (data) {
console.log(data);
}});
But how can I trigger that function when event_add is clicked?
To run your updated ajax code on click, add #event_add click event handler and run your code inside it.
$('#event_add').click(function(e){
e.preventDefault(); //suppress default behavior
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas")', // don't hard code your urls
data: { region: $('#lstRegion option:selected').html(), solicitud:
$('#lstSolicitud option:selected').html() }, // pass the value to the id parameter
dataType: 'json', // your returning a view, not json
success: function (data) {
console.log(data);
}});
});
Hi Try the below updated code:
$('#event_add').click(function(e){
var regionval = $('#lstRegion option:selected').html(),
var solicval = $('#lstSolicitud option:selected').html(),
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas", new { lstRegionValue = regionval, lstsolicitudValue =solicval})',
});
});
Note : I didnt test the code, but hope that it should work for you
Controller code:
public ActionResult GetTareas(string lstRegionValue, string lstsolicitudValue)
{
}
Hope it helps , thanks
I have a newsletter subscription form in a website I'm creating (it's part of the layout) and I'm using Html.Action() in my layout.cshtml file to call my Subscribe() action method. The method has 'two' versions: one for get and other for post requests.
Problem:
the Subscribe() POST action method gets called whenever any other form is submitted - I don't want that: it should only be called when someone clicks on the 'subscribe' button (then there's an ajax call to update the page without reloading)
For instance, in my contacts page, when I submit the form, the Subscribe() post method also gets called
I'm not sure why this happens but I believe it is because there's a post request and hence my Subscribe() POST method gets called automatically instead of the Subscribe() GET one.I tried using Html.Partial for this instead but it doesn't work because I have to pass a model to the partial view through the layout.cshtml file
_layout.cshtml:
// more code
#Html.Action("Subscribe", "Newsletter", new { area = "" })
// mode code
NewsletterController:
public ActionResult Subscribe() {
NewsletterSubscribeVM model = new NewsletterSubscribeVM();
return PartialView("NewsletterSubscription", model);
}
/// always gets called, even when it shouldn't
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Subscribe(NewsletterSubscribeVM subscriber) {
string message;
if (!ModelState.IsValid) {
message = "Ops! Something went wrong.";
return Json(message, JsonRequestBehavior.AllowGet);
}
Newsletter sub = new Newsletter { Email = subscriber.SubscriberEmail };
this._service.Add(sub);
message = "Thank you for subscribing!";
return Json(message, JsonRequestBehavior.AllowGet);
}
}
NewsletterSubscription.chtml
#model Web.ViewModels.NewsletterSubscribeVM
#using (Html.BeginForm("Subscribe", "Newsletter", new { area = "" }, FormMethod.Post, new { id = "newsletter-form", #class = "col-xs-12" })) {
#Html.AntiForgeryToken()
#Html.Label("Subcribe!", new { id = "newsletter-msg", #class = "col-xs-12 no-padding" })
#Html.TextBoxFor(m => m.SubscriberEmail, new { placeholder = "Email", #class = "col-xs-7", id = "newsletter-box" })
<button id="newsletter-btn" class="col-xs-1">
<i class="fa fa-arrow-right absolute-both-centered" aria-hidden="true"></i> </button>
}
Javascript:
$('#newsletter-btn').click(function (e) {
var form = $('#newsletter-form');
e.preventDefault();
// if the user has inserted at least one character and the 'thank you' msg isn't showing yet:
if ($('#newsletter-box').val().length != 0 && $('#subscription-status-msg').length == 0) {
$.ajax({
method: "POST",
url: "/newsletter/subscribe",
data: form.serialize(),
dataType: "json",
success: function(data) {
$('<div id="subscription-status-msg" class="col-xs-12 no-padding">' + data + '</div>').appendTo($("#newsletter-form")).hide().fadeIn(500);
}
})
}
})
Thanks in advance!
I'm trying to upload a file then retrieve its content as JSon
My controller :
controller.cs
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
List<string> list = doStuff(file);
return Json(list);
}
My view :
view.cshtml
#using (Html.BeginForm("Upload", "Files", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="file" name="file" />
<input type="submit" name="Upload" value="Upload" />
}
When I upload a file it propose me to download a JSON file, but what I want is to set a javascript variable with this JSON so I can use it directly on my webpage.
I believe that the best solution is to use an ajax form.
See the example below:
Controller:
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
return Json(new { ReturnMessage = "Success!!!!!" + file.FileName});
}
View:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { #id="formUploadFile", #onsubmit = "return SubmitFormWithFile();" }))
{
#Html.TextBox("file", null, new { #type = "file", #id = "file" })
<button type="submit">Send</button>
}
Javascript:
function SubmitFormWithFile() {
var form = $("#formUploadFile");
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: new FormData(form[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
alert("Before Send");
},
success: function (dataResult) {
//set its variable here...
//the dataResult is returned json...
alert(dataResult.ReturnMessage);
},
error: function () {
alert("Error");
}
});
return false;
}
I have Index view:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
<title>MsmqTest</title>
</head>
<body>
<div>
<input type="submit" id="btnBuy" value="Buy" onclick="location.href='#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })'" />
<input type="submit" id="btnSell" value="Sell" onclick="location.href='#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })'" />
</div>
<div id="msmqpartial">
#{Html.RenderPartial("Partial1", Model); }
</div>
</body>
</html>
and partial:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<p>
Items to buy
#foreach (var item in Model.ItemsToBuy)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
<p>
<a>Items Selled</a>
#foreach (var item in Model.ItemsSelled)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
And controller:
public class MsmqTestController : Controller
{
public MsmqData data = new MsmqData();
public ActionResult Index()
{
return View(data);
}
public ActionResult BuyItem()
{
PushIntoQueue();
ViewBag.DataBuyCount = data.ItemsToBuy.Count;
return PartialView("Partial1",data);
}
}
How to do that when i Click one of button just partial view render, now controller wants to move me to BuyItem view ;/
The first thing to do is to reference jQuery. Right now you have referenced only jquery.unobtrusive-ajax.min.js but this script has dependency on jQuery, so don't forget to include as well before it:
<script src="#Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Now to your question: you should use submit buttons with an HTML form. In your example you don't have a form so it would be semantically more correct to use a normal button:
<input type="button" value="Buy" data-url="#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })" />
<input type="button" value="Sell" data-url="#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })" />
and then in a separate javascript file AJAXify those buttons by subscribing to the .click() event:
$(function() {
$(':button').click(function() {
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
success: function(result) {
$('#msmqpartial').html(result);
}
});
return false;
});
});
or if you want to rely on the Microsoft unobtrusive framework you could use AJAX actionlinks:
#Ajax.ActionLink("Buy", "BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
#Ajax.ActionLink("Sell", "SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
and if you want buttons instead of anchors you could use AJAX forms:
#using (Ajax.BeginForm("BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Buy</button>
}
#using (Ajax.BeginForm("SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}
From what I can see you have already included the jquery.unobtrusive-ajax.min.js script to your page and this should work.
Maybe not the solution you were looking for but, I would forget about partials and use Javascript to call the server to get the data required and then return the data to the client as JSON and use it to render the results to the page asynchronously.
The JavaScript function;
var MyName = (function () {
//PRIVATE FUNCTIONS
var renderHtml = function(data){
$.map(data, function (item) {
$("<td>" + item.whateveritisyoureturn + "</td>").appendTo("#msmqpartial");
});
};
//PUBLIC FUNCTIONS
var getData = function(val){
// call the server method to get some results.
$.ajax({ type: "POST",
url: "/mycontroller/myjsonaction",
dataType: "json",
data: { prop: val },
success: function (data) {
renderHtml();
},
error: function () {
},
complete: function () {
}
});
};
//EXPOSED PROPERTIES AND FUNCTIONS
return {
GetData : getData
};
})();
And on the Server....
public JsonResult myjsonaction(string prop)
{
var JsonResult;
// do whatever you need to do
return Json(JsonResult);
}
hope this helps....