在asp mvc中将参数从View传递给Controller

时间:2015-02-05 08:51:17

标签: asp.net asp.net-mvc asp.net-mvc-4

我正在尝试将参数从视图传递到控制器,

这是我的观点:

@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>
  }     
}

我的行动方法:

在提交时,它会到达操作方法,但我无法获得每个价格的PriceId

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

网址路由:

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

我可以知道我在做什么错吗?

3 个答案:

答案 0 :(得分:1)

请在cshtml页面中使用以下内容

  @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>

并在控制器中

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

请根据方法参数和价格实体更改参数 希望这会有所帮助。

答案 1 :(得分:1)

我建议你摆脱Html.BeginForm()。只需离开for...loop并定义您的&#34;获取礼物&#34;像这样的按钮:

<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(@(pricedetails.PriceId))'" />

然后,在Get Gift按钮所在的视图文件的底部,定义一些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>

通过使用ajax调用来获取礼物数据,您不必提交任何内容。这使得事情变得更容易。按Get Gift按钮只会进行ajax呼叫。

我没有时间自己尝试一下,但希望上面的例子可以让你开始运行。

编辑:

我设法潜行一段时间来提出一个例子。

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.
    }
}

查看

@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>

希望这会对你有所帮助。

答案 2 :(得分:0)

我认为你应该在这里纠正

<input type="button" name='giftid' value="Get Gift"
       onclick="location.href='@Url.Action("Index",  new { id = pricedetails.PriceId })'" />