Correctly using quote marks in MVC view Razor - asp.net-mvc

I am having some difficulties using quote marks in ASP.Net Razer view as I keep ending up with them replaced with '
If I for example type:
#{string test = "String 'with' quotes"}
#test
I end up with:
String 'with' quotes
In the above example this is desirable.
However, take this second example:
#{string myJSFunction = myJSFunction('myString')"}
#myJSFunction
I end up with:
myJSFunction('myString')
Which results in a broken javascript function.
I have tried excaping the quote marks with \, but they don't seem to be having any effect.
Here is the actual problem I am faced with:
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = #myJSFunction
}))
Any advice?

The # operator always HTML-encodes strings. If you want the raw string value, use #Html.Raw(myJSFunction).

In razor, # will encode and render. Try Html.Raw method. This method returns markup that is not HTML encoded.
#Html.Raw(myJSFunction)
So if you want to execute the function in a script block, you can do it like
#{string myJSFunction = "alert('Rise and Shine')";}
<script type="text/javascript">
#Html.Raw(myJSFunction)
</script>

The solution to your issue is already mentioned (Html.Raw()) but I'm not sure why you're using # in your code sample given. From the looks of it you're already in code block when you try to assign it, so why use the razor.
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = #myJSFunction
}))
should be
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = myJSFunction
}))
# is what tells the StreamWriter for the page to write the result to the response, and as such is intended to be injected into the page after HtmlEncoding. Using Html.Raw bypasses the Html encoding aspect but in your case you're not writing it the page directly yourself, you're letting Html.BeginForm handle that, so you don't need the # in the assignment of your OnComplete function.
UPDATE: Ok, another thing I forgot to mention is that the methods passed to the AjaxOptions are Javascript functions only, no parameters by the looks of it. Parameters are passed in automatically by the Unobtrusive scripts that handle all the wiring. So your form should look like this...
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = "myJSFunction"
}))
And it will handle the rest. If you need to pass additional parameters in the myJSFunction function, you're probably going to have to expose them via other means. Either as a javascript variable or by associating it with some other element and access it using $("elementselector").data("dataAttributeName") (this is my preferred and suggested method). One of the common requested modifications made to the unobtrusive ajax JavaScript libraries (I wish Microsoft would just adopt this change and be done with it) is to set the context of this to the element that triggered the ajax event. So for in this case it would make this equal to the form element. With all this in mind, here's my recommendation.
First:
Modify your Unobtrusive Ajax script file so that the source element gets assigned to the this keyword so that's it's available in your JavaScript handling the unobtrusive events.
This question outlines what it involves (one line added to the file)
Second:
Add your string to one of the data attributes on your form
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new {id = ViewBag.InputResourceID},
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = "myJSFunction"
},
new { data_parameter_name = "myString" }))
Third:
Access your parameter from inside of the javascriptfunction handling your event.
<script>
function myJSFunction(data, textStatus, jqXHR)
{
//data, textStatus and jqXHR are set for you by the unobtrusive ajax script file automatically, feel free to use them
var parameter = $(this).data("parameterName");
alert(parameter);
}
</script>

Related

How to avoid page refresh in asp.net mvc

without refresh
When I click on any page link of the partial view, that related page should be displayed in the render body part without any page refresh. How can I do that ?
You can use the AJAX helper that is used in conjunction with unobtrusive ajax
You can find more information at this page
Install Microsoft.jQuery.Unobtrusive.Ajax NuGet package
Include the script on _Layout <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
You then use the HTML Helper with specific options
Code Sample
#Ajax.ActionLink("View All Student Info", "AllStudent", "Home", new AjaxOptions
{
UpdateTargetId = "divAllStudent",
OnBegin = "fnOnBegin",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
LoadingElementId = "imgloader",
OnSuccess= "fnSuccess",
Confirm="Do you want to get all student info ?????"
},
new { #class = "btn btn-default" })
Then in the controller add a specific [GET] Route (WebAPI)
Code Sample
[HttpGet]
public PartialViewResult AllStudent()
{
using (TempEntities db = new TempEntities())
{
var objAllStudent = db.StudentInfoes.ToList();
return PartialView("AllStudent", objAllStudent);
}
}
The options UpdateTargetId is the HTML ID container of where the AJAX result will put the result content. Usually you want to use Replace. You can use OnBegin and OnSuccess as Javascript methods that do things like show loaders, hide loaders, etc etc

ASP.NET MVC Ajax ActionLink ActionName vs AjaxOptions URL difference?

See this simple Razor markup:
#Ajax.ActionLink("Load something", "LoadPartialView", new AjaxOptions
{
UpdateTargetId = "here",
LoadingElementId = "loading",
OnBegin = "show_loading",
OnComplete = "hide_loading",
Url = "/Home/LoadPartialView2"
})
I notice if I include LoadPartialView as a parameter in the ActionLink and also specify a URL LoadPartialView2 in AjaxOptions, the generated link will invoke the LoadPartialView2 action. The optional Url takes priority:
If Url was removed, then clicking the link will invoke
LoadPartialView.
If ActionName parameter was set to null, vice versa,
LoadPartialView2 will be invoked.
When would the URL in AjaxOptions be used over ActionName?
I noticed if I set Url to http://www.google.co.uk it doesn't load the page into the div tag (id="here").
Thanks!

How to pass an actionlink's results to a partialview placeholder?

Okay, so in my page I have a list of links:
#foreach (var item in Model)
{
#Html.ActionLink(item.Name, "Recruitments", new { Id = item.Id })
<br />
}
And what I want is for the partialview to return somewhere else on the page, in a placeholder I've set aside.
Is this possible? Or do I have to use jquery ajax calls instead somewhere?
you can #Ajax.ActionLink in asp.net mvc, it has different overloads you can use according to your requirements here is the code:
#Ajax.ActionLink("ActionName", // action name
"Recruitments", //controller name
new { Id = item.Id }, // route values
new AjaxOptions { HttpMethod = "GET", //HttpMethod Get or Post
InsertionMode = InsertionMode.Replace, // Replace content of container
UpdateTargetId = "Container", // id of element in which partial view will load
OnComplete = "Completed();" }) // js function to be executed when ajax call complete
<div id="Container">
</div>
<script>
function Completed()
{
alert("completed");
}
</script>
I did had a problem with partial for your problem post some code so I understand your problem.
Either you should use a razor helper, either you simply use jquery to manipulate the dom.
note that jquery is pretty simple
$("#selectorOnYourPlaceHolder").html($("#selectorOnYourLinks").html());
$("#selectorOnYourLinks").html("")
You want to do this with Ajax:
$.ajax({
type: "GET", url: "somePageOrHandler.aspx", data: "var1=4343&var2=hello",
success: function(data)
{
$('#someDivInPlaceHolder').html( data);
}
});

data-val attributes not generated in partialview created with Html.ActionLink in ASPNET MVC3

I've this structure
View
Html.RenderPartial (1)
Html.RenderPartial (2)
Then in each one of those Partial Views I have
#Ajax.ActionLink("Edit", "EditMethod", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divEditContent"
}, new { #class = "my-edit" })
And when clicked it renders another partial,replacing the div "divEditContent" with something like:
public PartialViewResult EditContactInformation()
{
return PartialView("_MyEdit", GetDetails());
}
_MyEdit partial has something like:
#using (Ajax.BeginForm("SaveContactInformation", "MyBsol", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divContactInformationContent"
}))
{
<script type="text/javascript">
$(function () {
$('form#ajaxForm').find('a.submit-link').click(function () {
$('form#ajaxForm').submit();
});
})
</script>
Save
#Ajax.ActionLink("Cancel", "CancelEdit", null, new AjaxOptions
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divContent"
}, new { #class = "my-cancel" })
#Html.TextBoxFor(model => model.Title, new { #class = "txt-input", placeholder = "Eg. Mr, Mrs, Ms" })
#Html.ValidationMessageFor(model => model.Title)
}
The problem is that data-val atttributes are not rendered for the input, BUT if I put the last partial (_MyEdit) where the Ajax.ActionLink (1) it DOES render them.
Is this a bug? Any workaround?
Thanks in advance! Guillermo
UPDATE
I've found something really interesting, if I go (in Chrome or Firefox with Firebug) and click on View Source I don't see data-val attributes, but if I click on Inspect Element I see them..weird...
If you want the data validation tags to be there, you need to be in a FormContext. Hence, if you're dynamically generating parts of your form, you need to include the following line in your partial view:
#{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); }
You then need to make sure you dynamically rebind your unobtrusive validation each time you add/remove items:
$("#form").removeData("validator");
$("#form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#form");

Read htmlAttribute in controller

I have Ajax.ActionLink with htmlAttribute param
<%= Ajax.ActionLink("cool", "ViewCategory", new { id = elem.ID }, new AjaxOptions { UpdateTargetId = "score_" + elem.ID.ToString() }, new { myAttr = 123 } )%>
How can I read this attribute in controller method?
You can't.
All the htmlAttribute param does is instruct the generation of additional attributes to be added to the anchor html with it is sent to the client. These attributes are not included in the request when the anchor is clicked.
Place the attribute along side the id new {id = elem.ID, UpdateTargetID = ...} this should be included in the URL.

Resources