pavilion pavilion - 4 months ago 64
Ajax Question

popup a dialog and submit partial view in mvc

So what I am trying to do here is that in the View,

  1. when I click on the button, I want to pass some values generated from the foreach loop (in my case Country and City) to the javascript function.

  2. Inside that javascript function, I want to open up a dialog(partial view) by passing those values (countryName, cityName) to the controller.

  3. Hence in my controller, it will pass those values to the partial view which will be appeared as a dialog and can submit the form.

I've tried with the version without the pop-up dialog (it worked), but having a hard time doing it with a dialog. #3 works btw, but I think I am having a trouble with #1 and #2. Any help would be appreciated. Thanks.


@model IEnumerable<test.Models.Employee>

<table class="table">

@foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.Country)
@Html.DisplayFor(modelItem => item.City)
<button onclick="OpenDialog(item.Country, item.City)">
Open Dialog

<div id="dialog"></div>

@section Scripts {
<script src="~/Scripts/jquery-ui-1.12.0.js"></script>

function OpenDialog(countryName, cityName) {
autoOpen: true,
width: 400,
resizable: false,
title: 'My Table',
modal: true,
open: function(event, ui) {

$(this).load('@Url.Action("getEmployee", "Employee", new
country = countryName,
city = cityName
buttons: {
"Close": function () {



public ActionResult getEmployee(string country, string city)
var viewModel = new EmployeeViewModel()
Country = country,
City = city

return PartialView("EmployeeDialog", viewModel);

Partial View:

@model test.ViewModels.EmployeeViewModel

@using (Html.BeginForm("PostEmployee", "Employee", FormMethod.Post))

@Html.HiddenFor(model => model.Country)
@Html.HiddenFor(model => model.City)
@Html.EditorFor(model => model.Comments)

<input type="submit" value="Submit"/>



@Url.Action() is razor code and is parsed in the server before its sent to the view. countryName and cityName are javascript variables and do not even exist at that point (they are not in scope). Change the code in the OpenDialog() function to

var url = '@Url.Action("getEmployee", "Employee")';
var data = { country: countryName, city: cityName };
$(this).load(url, data); 

As a side note, there is really no need to be calling the server each time to return values that you already have in the view. You could just render the form in the dialog initially (for a default EmployeeViewModel and then in the OpenDialog just set the values of the inputs for properties Country and City, for example $('#Country').val(countryName);