I know that this question was answered many times, but since I don't know much about javascript, and this is my first website, I followed the answer in this link. This is my code so far:
<li>#Html.ActionLink("Save","SaveClass",new { path2=Model.path,code="xxx"},new { id="save"})</li>
#Html.TextAreaFor(m=>m.code, new { id = "code" })
<script>
$("#save").click(function(evt) {
var fakedUri = $("#save").attr("href");
alert($('#code').val());
var uri = $("#save").attr("href").replace("xxx", $("#code").val());
});
</script>
And this is my controller:
public ActionResult SaveClass(string path2,string code)
{
modelSC.path = path2;
modelSC.code = code;
System.IO.File.WriteAllText(Server.MapPath(modelSC.path), code);
return RedirectToAction("Index");
}
The code always saves 'xxx' to the file, and throws:
The requested content appears to be script and will not be served by
the static file handler.
How can I get it to work?
ActionLink helper generates a link and clicking on that will issue a GET request. Looks like you are trying to send the value of the text area through querystring to the next action method. But GET might not be the best solution to handle that. Querystring has a limit on how much data it can handle (varies for different browsers).
Ideally you should do a form submit, If you do not prefer a button, but want a link to initiate the form submit, that is possible with a little javascript.
#using(Html.BeginForm("SaveClass","YourControllerName"))
{
#Html.TextAreaFor(m=>m.code)
#Html.HiddenFor(s=>s.path)
#Html.ActionLink("Save","SaveClass","YourControllerName",null,new { id="save"})
}
Now in your javascript, when click on the link, stop the default behavior (the default GET Action) and then submit the form where the clicked link is present. We can use the closest() method.
$(function(){
$("#save").click(function(e){
e.preventDefault();
$(this).closest("form").submit();
});
})
Make sure you use the correct parameter name (matching with the input name)
public ActionResult SaveClass(string path,string code)
{
// to do : return something
}
Related
I have this code:
#if (!string.IsNullOrWhiteSpace(Model.ErrorMessage))
{
<script>
$('#modalError').modal('show');
</script>
Response.Write("<script>alert('hello');</script>");
HttpContext.Current.Response.Write("<script>alert('hello');</script>");
}
Where check if Model.Error Message is different from empty, so I an alert to the user, but none of the forms submitted by the condition if this working, how can it be done?
already I tried so:
#if (!String.IsNullOrEmpty(ViewData["erro"] as string))
{
<script>alert(#ViewData["erro"]);</script>
}
This and a part of the view.
My controller this way:
public ActionResult Login(LoginViewModel model, SignInMessage message)
{
if (!String.IsNullOrEmpty(model.ErrorMessage))
ViewData["erro"] = !String.IsNullOrEmpty(model.ErrorMessage) ? model.ErrorMessage : null;
return this.View(model);
}
I want to display a javascript message because I will use the modal Bootstrap
#Alexandre Lima,
As pointed out in comments by others and I agree too, not sure if your approach is right or if it is then we need more information, that said, You have the following options
Use simple data validations on your view models to notify users of
an invalid email - this is built into MVC for you - MVC's data
annotation. Here are links
http://www.asp.net/mvc/overview/older-versions-1/models-data/performing-simple-validation-cs
From your comment, looks like you want to display something on login
failures , meaning your server code got back saying Auth failed,
if that is the case, am assuming here you have something like this
on your controller code
public ActionResult Login(LoginModel login)
{
if(ModelState.IsValid)
{
//you call your service to get back the result
if(!NotAValidUser)
{
ModelState.AddModelError("LoginFailed", "The user name and or password is incorrect.")
}
}
}
in your View
#Html.ValidationMessage("LoginFailed") // this will display the above message
If it's a View, then you might be better off using Javascript/JQuery. To do that, you'll need to add a hidden field somewhere in your HTML and set the value to Model.ErrorMessage. Like this:
<input type="hidden" id="hdError" value="#Model.ErrorMessage" />
Then at the end of your HTML body, you add the Javascript code:
<script>
$(function() {
var errorStr = $("#hdError").val();
if (errorStr) {
alert("hello"); //or any other alert message
}
});
</script>
I got "MultiLanguageProvider" which is ordinary C# class, not Controller or Model. The idea is when user clicks Change language - it must call back server-side void ChangedLanguage() on MultiLanguageProvider instance. This doesn't work at all:
#MultiLanguageProvider.Instance.SelectAppropriate("на русском", "in english")
- 'cause all the code inside #{ } get executed immideately - at the time of page-load. I am not informed about AJAX, so maybe someone of u can show me the right direction to do this simply job?
I don't understand which one you are trying to invoke on anchor tag click. But if I understand the essence of your question, you are trying to call some server side method to change the language, and here I assume you want to save the language selection that was made on user interface (UI). If this is what you are looking, on client side, you do the changes suggested by Stephen Muecke. On server side, you need to add a [HTTPPOST] action method on controller something like:
public ActionResult SwapLanguage(LanguageViewModel languageViewModel)
{
//do the save action => like saving to database
return Json(new { data = {urlToRedirt: "/someUrl_GeneratedVia_UrlHelper"},
status = "success",
message = "Language Changed Successfully" }, JsonRequestBehavior.AllowGet);
}
}
On Client side:
$('#swaplanguage).on('click', function(event) {
event.preventDefault();
$.post( '#Url.Action("SwapLanguage")', function( data ) {
// Handle the server side response here.
// Like if you want to redirect, use something like:
// window.location = data.urlToRedirt;
});
}
Of course, you need to handle error conditions on both client as well as server side.
If you don't want to save anything, and you just want to redirect user to some url based on the language user selects, then your onclick event handler is something like:
$('#swaplanguage).on('click', function(event) {
urlToRedirect = 'url_to_redirect' + '/' + $('#languageDropDownId').val();
window.location = urlToRedirect;
}
Finally, your anchor tag is:
<a id="swaplanguage">Change Language</a>
Hope that helps.
I am having a hard time deciding on an appropriate way to Perform some server side functionality and then redirecting to the same View in my ASP.Net MVC project.
I am trying to call an Action after the selected index changed client side event of my combobox.
One way I can think of is to change the window.location to the url of my Action and pass the data i need via the query string like this
function SelectedIndexChanged(s,e)
{
window.location.href = "/MyController/MyAction?" + s.GetValue();
}
I also see lots of people saying you should use jquery ajax for this
function SelectedIndexChanged(s,e)
{
$.ajax({
url: 'MyController/MyAction',
data: { value: s.GetValue() },
success: function(){
alert('Added');
}
});
}
My Action looks something like this where i set some cookie values using the value and Set View bags values depending on the selected index.
public ActionResult SelectedIndexChanged(string value)
{
//Do some processing
//Set cookie values
SetViewBags(value);
return Redirect(Request.UrlReferrer.ToString());
}
Is there a better approach to accomplish my task, I am leaning more towards changing the location.href as it is simpler, but i'm not sure if this is good practice?
EDIT
To Clarify this Combobox is a Devexpress MVC extension so I will have to handle the "SelectedIndexChanged" client side event.
This Combobox is also on my layout page so it appears on every view in my project. So when it is changed i will need to to call the same Action no matter what page it is on
As you've indicated that your form is in your layout (not a view), I recommend you look at using a view partial. Fortunately, MVC has already provided an example with their view partial (can't remember the name) that has the login and logout buttons. If a user clicks logout, some javascript is fired and the form is submitted. This will redirect the user; however, you could also send the original address (referrer) as a parameter to your server method and then redirect to that page afterward.
You could always use an Html.Action
function SelectedIndexChanged(s,e)
{
#Html.Action("ActionName", "ControllerName", {optional route values})
}
I have an MVC 5/C# application. I have a button on a form that allows the user to delete a record from the DB. When clicked the button calls the JS function below. The HTML that allows the user to delete the current row is:
<a class="btn btn-default" href="javascript:DeleteLocation(#Model.RowId);">Delete</a>
The JS function looks as follows:
function DeleteLocation(rowId) {
var url = "/UserLocation/Delete";
var redirectUrl = "/UserLocation/Index"
$.get(url, { rowId: rowId }, function () {
$.get(redirectUrl);
});
}
My C# Delete method looks as follows:
[Authorize]
public void Delete(int rowId)
{
UserLocationData userLocationData = new UserLocationData();
userLocationData.Delete(rowId);
}
Half of this is working perfectly. My C# method is getting called when the user clicks the button. However, after the delete, the page I want to redirect to isn't getting displayed. I tried putting a RedirectToAction in the C# method but that didn't work either. I don't have a large amount of experience with JS or jQuery so it's quite possible my JS is just wrong. Or there could be a much better way to do this.
window.location should be used to send the user to another page.
window.location.replace("http://yourwebsite.com");
More details here
Use window.location
window.location = redirectUrl;
I would like to have a page that would contain:
hyperlik "Add new country".
After clicking this link by user, dropdown list with names of countries should appear. However this hyperlink should stay on this page. When user click this hyperlink once again, second dropdown list with exactly the same names should appear. This should be repeat as long as user clicks hyperlink.
It is important that this page shouldn't be reloaded.
Does anyone has any idea how can it be made?
The typical way to achieve this is to have your Add new country link trigger an ajax call out to a page you create which will provide the data for your list.
The preferred method these days seems to be having that page you call build up a JSON response, then your callback on the ajax method where you called it can populate that data into a drop down.
The page you call from AJAX could be something simple like this:
protected override void Render(HtmlTextWriter writer)
{
Dictionary<string, int> myStuff = new Dictionary<string, int>();
myStuff.Add("country1", 1);
myStuff.Add("country1", 2);
JavaScriptSerializer jss = new JavaScriptSerializer();
Response.Write(jss.Serialize(myStuff.ToList()));
Response.ContentType = "application/json";
}
Use this jQuery on your main page:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
getCountries();
});
});
function getCountries() {
$.ajax({
url: "ApiPage.aspx",
dataType: "json",
success: function (data) {
for (var i in data) {
$("#myDropDown").append($('<option></option>').val(data[i].Value).html(data[i].Key));
}
}
});
}
</script>
Tested and working. (in a simplified example) I did have to convert from Dictionary to List for the json serializer to make it an array as desired. See the updated Serialize call. There is also some validation, e.g. did the ajax call return real data?, that would need added to a real life implementation.
It looks like you are doing it a least approximately right.
in the HTML if you have some tag that surrounds the area you want the drop down box to then it is simple.
for example:
in HTML:
Add new country
<div id="dropdownarea"></div>
in javascript:
function addDD(){
document.dropdownarea.innerHTML += "HTML code for the drop down that you want";
}