2

Although I manage to send the grid's selected row id to the controller, the url for opening action view cannot be built up (it is created /Controller/Action instead of /Controller/Action/id. So, when I try to open the view with /Controller/Action/id it is open, but it cannot be opened by button click as below.

View:

<input type="button" id="btn" name="name" value="send to Server!" />

<script>
$('#btn').click(function () {
    var items = {};
    var grid = $('#Grid').data('kendoGrid');
    var selectedElements = grid.select();
    var item = grid.dataItem(selectedElements[0]);

    $.ajax({
        type: "POST",
        data: item.ID, //I obtained the id properly
        url: '@Url.Action("CreateParticipant", "Training")',
        success: function (result) {
            //console.log(result);
        }
    })
})
</script>


Controller:

// GET: /Training/CreateParticipant/5
public ActionResult CreateParticipant(int? id)
{
    Training training = repository.Trainings.FirstOrDefault(m => m.ID == id);
    if (training == null)
    {
        return HttpNotFound();
    }
    var trainingParticipantViewModel = new TrainingParticipantViewModel(training);
    return View(trainingParticipantViewModel);
}


Route.config:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            //defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            defaults: new { controller = "Multiplier", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Is there another example as above to pass the parameters or is there any mistake on the code above? Thanks in advance.

Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63

3 Answers3

2

Javascript

$('#btn').on("click",function () {
    var items = {};
    var grid = $('#Grid').data('kendoGrid');
    var selectedElements = grid.select();
    var item = grid.dataItem(selectedElements[0]);

        $.ajax({
            type: "GET",
            data: item.ID, //I obtained the id properly
            url: '@Url.Action("CreateParticipant", "Training")/'+item.ID,
            datatype:'html',
            success: function (result) {
              alert(result)
            }
        })
    })

Or use

$('#btn').on("click",function () {
    var items = {};
    var grid = $('#Grid').data('kendoGrid');
    var selectedElements = grid.select();
    var item = grid.dataItem(selectedElements[0]);

    window.location.href= '@Url.Action("CreateParticipant", "Training")/'+item.ID; 
});

Hope this helps.

Frebin Francis
  • 1,905
  • 1
  • 11
  • 19
  • I obtained the related view's html in alert. However, after pressing OK button or commenting out this alert line, the related view still cannot be rendered. I tried on another browser by clearing all the history and cookies of it, but still no change. It is really unbelievable (I have already had many views and opened these views by means of different option i.e. hyperlink, image, button, etc. – Murat Yıldız Feb 26 '15 at 14:16
  • where you want to show this html ? you have to append the html to any of the content tag like div to render the html – Frebin Francis Feb 26 '15 at 14:17
  • In CreateParticipant view as called in the controller above. – Murat Yıldız Feb 26 '15 at 14:22
  • 1
    just try to out window,location.href= '@Url.Action("CreateParticipant", "Training")/'+item.ID inside button click remove the ajax call.i will update my answer. – Frebin Francis Feb 26 '15 at 14:25
  • Yes, it worked :) But what is the difference? Anyway, many thanks for your kind helps and efforts. I voted not only your answer, but also all of the useful comment :) Kind regards... – Murat Yıldız Feb 26 '15 at 14:31
  • 1
    see $.ajax is using for asynchronously loading the page but window.location.href is for normal loading that's the difference. – Frebin Francis Feb 26 '15 at 14:33
  • try to learn what is Ajax man, it will help you in future.Thanks for voting. – Frebin Francis Feb 26 '15 at 14:34
  • Ok, I will :) On the other hand, may there be any disadvantage to use window.location.href instead of $.ajax? – Murat Yıldız Feb 26 '15 at 14:34
  • it's not about advantage or disadvantage, These are the two different methods used to access a resource from server, but $.Ajax will load the resource fast – Frebin Francis Feb 26 '15 at 14:37
1
.ToolBar(toolbar =>
    {
        toolbar.Template(@<text>
            <div class="toolbar">
            @(Html.Kendo().Button()
                .Name("addbtn")
                .Content("Add New")
                .HtmlAttributes(new { type = "button", @class = "k-primary k-button k-button-icontext js-myKendoButton", @data_id = @Model.YourID, onclick = "onClick()" })
            )
            </div>
        </text>);
    })

And then you will grab the data-attribute with jQuery.

$('.js-myKendoButton').attr('data-id');

More here: How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

Community
  • 1
  • 1
Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54
  • Thanks for reply. There is an error on " @data_id = @Model.ID" section due to the fact that it is a list instead of one record. On the other hgand, I had tried to use id values in HtmlAttributes, but get the same error. So, I think it is better for this situation to use a javascript methof and call it from HtmlAttributes. Any other solution? – Murat Yıldız Feb 26 '15 at 11:03
0
<script>
$('#btn').on("click",function () {
    var items = {};
    var grid = $('#Grid').data('kendoGrid');
    var selectedElements = grid.select();
    var item = grid.dataItem(selectedElements[0]);

    $.ajax({
        type: "POST",
        data: {ID  : item.ID}, //I obtained the id properly
        url: '@Url.Action("CreateParticipant", "Training")',
        success: function (result) {
            //console.log(result);
        }
    })
})
</script> 

use this ,i hope this will be help you

Shahzad Khan
  • 432
  • 2
  • 14
  • thnanks a lot, it is much more pretty to obtain ID parameter and the id parameter can be passed to controller. However the related view cannot be called. On the other hand, when I type the calling address as http://localhost:23879/Training/CreateParticipant/2 it works. But when calling by button it behave as I call http://localhost:23879/Training/ with no action and no id parameter. So, there is no problem on viewmodel side etc. Any idea? – Murat Yıldız Feb 26 '15 at 12:37
  • welcom,if id is nullable so no affect on yours model but first thingn is first prepared your model if id is null. – Shahzad Khan Feb 26 '15 at 12:42
  • I checked if id is null in the controller method and there is no problem regarding to id value. – Murat Yıldız Feb 26 '15 at 12:43
  • Okay , so what is your next scenario dude? – Shahzad Khan Feb 26 '15 at 12:45
  • Rendering the view called in the controller method. – Murat Yıldız Feb 26 '15 at 13:03
  • 1
    check id is not null and data is find then show the specific view other wise rendering the same view. – Shahzad Khan Feb 26 '15 at 13:06
  • I checked many times and the related data is found, then trainingParticipantViewModel is loaded with data. However, I am not sure if there is one more step that I should do i.e. calling a method in success section in the javascript. – Murat Yıldız Feb 26 '15 at 13:45
  • I also add an alert to the success section and it is fired. The only problem seems to be that the rendering actions does not work. – Murat Yıldız Feb 26 '15 at 14:04
  • first create the `
    ` ,then hit your specific actionresult for create or edit so actionresult return to you partialview(model) and then append your View / partailveiw with `$("id").empty().append(response)`
    – Shahzad Khan Feb 27 '15 at 01:09