2015-02-05 2 views
0

Я пытаюсь передать параметр из поля зрения на контроллер,параметр перейти от View контролеру в осины MVC

Это мой Вид:

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

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

Могу ли я знаю, что не так я делаю?

+0

то, что вы делаете, совершенно неверно. вы не можете использовать onclick = "location.href = '@ Url.Action (" Index ", new {id = priceetails.PriceId})'", чтобы отправить на POST-метод –

+0

У вас нет элементов управления в вашей форме! и почему вы делаете и отправку, и перенаправление? –

+0

@frebin francis, спасибо, хорошо, я удалю форму, но как можно передать метод PriceId to Action – stom

ответ

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

Это делает перенаправление пустой страницы, на которой будет отображаться предупреждение! Я сомневаюсь в том, что хочет OP. –

+0

Вы хотите показать окно предупреждения на той же странице? –

+0

@frebin francis, ya вот что мне нужно – stom

0

Я думаю, вы должны исправить здесь

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

@Praves Kawser, когда я использую кнопку, View использует Priceid как индекс страницы и перенаправляет на http: // localhost: 21747/Index/23, но мне нужно предупредить пользователя перед перенаправлением. – stom

1

Я предлагаю вам избавиться от Html.BeginForm(). Просто оставьте for...loop и определить свою кнопку «Получить подарок», как это:

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

У меня нет времени попробовать это самостоятельно, но, надеюсь, приведенный выше пример должен вас поднять.

EDIT:

мне удалось проникнуть в какое-то время, чтобы придумать пример.

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> 

Надеется, что это помогает.

+0

@ оцените ваши усилия, я новичок в ajax я должен дать попробовать – stom

Смежные вопросы