开发者

Maintaining Index Value with Partial Views in ASP.NET MVC2 using SPARK

开发者 https://www.devze.com 2023-02-02 04:07 出处:网络
I am looking for a way to save index information when iterating through items in a ASP.net MVC 2 using the SPARK view engine.I often have a partial view that iterates through items and a button to add

I am looking for a way to save index information when iterating through items in a ASP.net MVC 2 using the SPARK view engine. I often have a partial view that iterates through items and a button to add new items.

I want to save the index after displaying the existing items and then pass it back to the same partial view to create and display a new item.

For instance:

  <div class="small">Enter the rooms associated with this facility.</div>
  <div class="add">
    <div id="rooms">
      <AddRoom each="var roomModel in Model.FacilityRooms"
               RoomModel="roomModel" Index="roomModelIndex" />
    </div>
    <div class="add">
      <a id="add开发者_开发知识库Room" class="add" href="events/room/add.mvc">Add a room</a>
    </div>
  </div>
  <p>
    <input type="submit" value="Submit" />
  </p>
</form>

Ideally I would like to save the Index from the AddRoom loop and use it for the "Add a room" button which calls the AddRoom view again with a blank room object.

I've tried utilizing Javascript and SPARK variables but can't seem to find a nice method of doing this. Any suggestions?

Cheers!


Answering this myself with the method I used, but I'm sure there are better ones still.

Here's what I did:

  1. Create a Javascript variable set to the size of the Rooms array in the View

    var roomIndex = ${Model.FacilityRooms.Count};
  2. Increment this variable in the Javascript function attached to the Add Room button. This way the index is incremented whenever Add is clicked, as it should be.

    $('#addRoom').click(function () {
    var a = $(this);
    a.addClass('loading');
    $.ajax({
        url: a.attr('href') + '?roomIndex=' + roomIndex++,
        cache: false,
        success: function (html) {
            $('#rooms').append(html);
            a.removeClass('loading');
        }
    });
    return false;
    

    });

  3. The javascript appends the index to the Add button's URL, so the index gets passed into the controller for the Add button. We then set it to assign it to the "Index" ViewData element so we can use the same view without any issues.

    [HttpGet]
    public ViewResult Add(int roomIndex)
    {
        ViewData["RoomModel"] = new EditFacilityRoomDto();
        ViewData["Index"] = roomIndex;
        return View();
    
    
    }
    

In the View we don't need to change anything else (other than adding the JavaScript variable in #1).

There's one way. Not sure if there is another better way.

Cheers.

0

精彩评论

暂无评论...
验证码 换一张
取 消