Reputation: 309
I am developing MVC application and using razor syntax.
I want to use HTML code in JavaScript in cshtml file, but I get confused about how to use double quotes in JavaScript in razor syntax. Is that matter?
This is line of code:
<span class="EmpName"> @Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { @style = "color:#1A6690;" })</span>
@Html.DisplayFor(ModelItem => item.CommentDateTime)
<span class="EmpName"><button type="button" id = "@item.Id" class="deleteComment">Delete</button></span>
And I have written below code in JavaScript, is that right?
success: function (data) {
$("p.p12").append
("<div style=\"background-color:#FAFAFA\";>Recently Added... <br /><a href=\"../../Employee/Details/" + data.OwnerID + "\">" + data.OwnerName + "</a>"
+ data.cmtDateTime + "<button type=\"button\" id = \" + data.Id + "\class=\"deleteComment\">Delete</button></span><br />" + data.msg + "</div>");
}
Upvotes: 0
Views: 427
Reputation: 1038730
and I have written below code in JScript is that right ?
No, it doesn't seem right. The generated HTML is broken. You need to be more careful about the syntax, things liks spaces between the attributes and the quotes are important. Also you seem to be hardcoding urls instead of using url helpers. Try like this:
$('p.p12').append(
'<div style="background-color:#FAFAFA;">Recently Added... <br /><a href="@Url.Action("Details", "Employee", new { id = "__id__" })'.replace('__id__', data.OwnerID) + '">' + data.OwnerName + '</a>' + data.cmtDateTime + '<span><button type="button" id=' + data.Id + ' class="deleteComment">Delete</button></span><br />' + data.msg + '</div>'
);
or as I suggested you here which IMHO is more correct approach.
or since you are using an AJAX call, instead of returning JSON from your controller action, return a ParialView in which you will correctly build the markup using proper HTML helpers.
Like this:
[HttpPost]
public ActionResult SomeAction(SomeViewModel args)
{
MyViewModel model = ...
return PartislView("_SomePartial", model);
}
and then inside your strongly typed partial (_SomePartial.cshtml
) build the markup without any string concatenations and spaghetti code mixing javascript and HTML:
@model MyViewModel
<div style="background-color:#FAFAFA;">
Recently Added...
<br />
@Html.ActionLink(Model.OwnerName, "Details", "Employee", new { id = Model.OwnerID }, null)
@HtmlDisplayFor(x => x.cmtDateTime)
<span>
<button type="button" id="@Model.Id" class="deleteComment">Delete</button>
</span>
<br />
@HtmlDisplayFor(x => x.msg)
</div>
Now all that's left in your AJAX success callback is to refresh the corresponding DOM section:
success: function(html) {
$('p.p12').append(html);
}
Upvotes: 1