Reputation: 582
I have a MVC simple application. I open dialog when button click. My popup content is a partial view.
AddUserPartialView.cshtml:
@model Demo.Models.AddUserViewModel
<script type="text/javascript">
function function1()
{
return {'p1':'try1','p2':'try2'};
}
function function2() {
return { 'p1': 'deneme1', 'p2': 'deneme2' };
}
</script>
<div id="showErrorMessage"></div>
<form id="myForm">
<div id="AddUserForm">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</div>
</form>
HomeController:
public ActionResult Index()
{
return View();
}
public PartialViewResult AddUserPartialView()
{
return PartialView("AddUserPartialView", new AddUserViewModel());
}
[HttpPost]
public JsonResult AddUserInfo(AddUserViewModel model)
{
bool isSuccess = false;
if (ModelState.IsValid)
{
//isSuccess = Save data here return boolean
isSuccess = true;
}
return Json(new { result = isSuccess, responseText = "Something wrong!" });
}
and index.cshtml:
<div class="row">
<div class="col-md-4">
<button class="AddUser">Add User</button>
<div id="AddUserForm"></div>
</div>
</div>
<script>
$(document).ready(function () {
$('.AddUser').on('click', function () {
$("#AddUserForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 1000,
resizable: false,
title: 'Add User Form',
modal: true,
open: function () {
$(this).load('@Url.Action("AddUserPartialView", "Home")');
},
buttons: {
"Add User": function () {
addUserInfo();
},
Cancel: function () {
$(this).dialog("close");
}
}
});
return false;
});
function addUserInfo() {
$.ajax({
url: '@Url.Action("AddUserInfo", "Home")',
type: 'POST',
data: $("#myForm").serialize(),
success: function (data) {
if (data.result) {
$(':input', '#myForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
} else {
$("#showErrorMessage").append(data.responseText);
}
}
});
}
});
</script>
if in function1() like this(with Enter character) : (in AddUserPartialView.cshtml)
return
{'p1':'try1','p2':'try2'};
I have error unexpected token. but function1 like this(No Enter character) :
return {'p1':'try1','p2':'try2'};
i have no error. It works fine. Why ?
Upvotes: 0
Views: 513
Reputation: 92709
You are a victim of the automatic semicolon insertion. If you have a code like this:
return
{'p1':'try1','p2':'try2'};
it is interpreted as:
return;
{'p1':'try1','p2':'try2'};
therefore the return
statement returns nothing, and the {
and }
in the next line are interpreted as a block statement, so in result it's something like this:
return;
'p1':'try1','p2':'try2';
See What are the rules for JavaScript's automatic semicolon insertion (ASI)?
Upvotes: 1