Asp.net Core 2 and Knockout.js - asp.net-mvc

Good morning I'm trying to add Anti Forgery Token to my application made using Knockout.js
This is my Model:
public partial class Course
{
[Key]
public int CourseID { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
}
This is my controller:
// POST: Home/Create
[HttpPost]
public string Create(Course course)
{
if (!ModelState.IsValid) return "Model is invalid";
_db.Courses.Add(course);
_db.SaveChanges();
return "Cource is created";
}
This is my View:
#model MVCCRUDKnockout.Models.Course
#{
ViewBag.Title = "Create";
}
<div class="form-horizontal">
<h4>Course</h4>
<hr>
<div class="form-group">
<label class="control-label col-md-2" for="CourseName">CourseName</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="CourseName" name="CourseName" type="text" value="" data-bind="value: CourseName">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="CourseDescription">CourseDescription</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="CourseDescription" name="CourseDescription" type="text" value="" data-bind="value: CourseDescription">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" data-bind="click: createCourse" value="Create" class="btn btn-default">
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Read")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/KOScripts/KOCreate.js"></script>
This is my Script:
$(function () {
ko.applyBindings(modelCreate);
});
var modelCreate = {
CourseName: ko.observable(),
CourseDescription: ko.observable(),
createCourse: function () {
try {
$.ajax({
url: '/Home/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this), //Here the data wil be converted to JSON
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
};
function successCallback(data) {
window.location.href = '/Home/Read/';
}
function errorCallback(err) {
window.location.href = '/Home/Read/';
}
Now I try to change the code:
1) adding [ValidateAntiForgeryToken] to the controller;
2) adding #Html.AntiForgeryToken() to the View.
My problem is that I cannot edit the Script to make it work properly.
How can I do this?

Related

ajax.beginform() not working asp.net .netFramework 4.7.2

i have trouble with my code, ajax beginForm does not make reference with the controller event, i have all the library.
the view :
#using MyWebsite.Models
#model UsersCLS
#{
ViewBag.Title = "Index";
}
<h1 style="text-align:center;">My Web Site</h1>
<section class="vh-100">
<div class="container py-5 h-100">
<div class="row d-flex align-items-center justify-content-center h-100">
<div class="col-md-8 col-lg-7 col-xl-6">
<img src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-login-form/draw2.svg" class="img-fluid" alt="Phone image">
</div>
<div class="col-md-7 col-lg-5 col-xl-5 offset-xl-1">
<form>
<!-- Email input -->
<div class="form-outline mb-4">
<input type="email" id="form1Example13" class="form-control form-control-lg" />
<label class="form-label" for="form1Example13">Email address</label>
</div>
<!-- Password input -->
<div class="form-outline mb-4">
<input type="password" id="form1Example23" class="form-control form-control-lg" />
<label class="form-label" for="form1Example23">Password</label>
</div>
<div>
<!-- Checkbox -->
<div class="form-check">
<input class="form-check-input"
type="checkbox"
value=""
id="form1Example3"
checked />
<label class="form-check-label" for="form1Example3"> Remember me </label>
</div>
</div>
<div>
Forgot password?
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg btn-block" data-bs-toggle="modal" data-bs-target="#exampleModal">
Check in
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
</div>
#using (Ajax.BeginForm("Add", "Login", null, new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "Create",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "error"
}))
{
<div>
#Html.Label("Name")
#Html.TextBox("name", null, new { #class = "form-control" })
</div>
<div>
#Html.Label("LastName")
#Html.TextBox("lastName", null, new { #class = "form-control" })
</div>
<div>
#Html.Label("Email")
#Html.TextBox("email", null, new { #class = "form-control", #type = "email" })
</div>
<div>
#Html.Label("UserName")
#Html.TextBox("userName", null, new { #class = "form-control" })
</div>
<div>
#Html.Label("Password")
#Html.Password("password", null, new { #class = "form-control" })
</div>
<button type="button" id="btnClose" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes </button>
}
<div id="error">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<script src="~/Scripts/jquery-3.6.0.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
this is the Model:
public class UsersCLS
{
[Display(Name ="Id")]
public int id { get; set; }
[Display(Name = "User")]
public string userName { get; set; }
[Display(Name = "Password")]
public string password { get; set; }
[Display(Name = "Name")]
public string name { get; set; }
[Display(Name = "Last Name")]
public string lastName { get; set; }
[Display(Name = "Email")]
public string email { get; set; }
}
And the Controller :
public ActionResult Index()
{
return View();
}
public string Add(UsersCLS usersCLS)
{
string answer = "";
if (!ModelState.IsValid)
{
}
else
{
using (var bd = new MyWebsiteEntities())
{
int count = 0;
using (var transc = new TransactionScope())
{
count = bd.Users.Where(p => p.UserName.Equals(usersCLS.userName)).Count();
if (count > 0)
{
answer += "<ul class='list-group'>";
answer += "<li></li>";
answer += "</ul>";
}
else
{
Users users = new Users();
users.UserName = usersCLS.userName;
SHA256Managed sha = new SHA256Managed();
byte[] bypass = Encoding.Default.GetBytes(usersCLS.password);
byte[] bycryptoPass = sha.ComputeHash(bypass);
string cryptoPass = BitConverter.ToString(bycryptoPass).Replace("-", "");
users.Password = cryptoPass;
users.Name = usersCLS.name;
users.UserName = usersCLS.userName;
users.LastName = usersCLS.lastName;
users.Email = usersCLS.email;
users.Enabled = true;
bd.Users.Add(users);
answer = bd.SaveChanges().ToString();
if (answer == "0")
{
answer = "";
}
transc.Complete();
}
}
}
}
return answer;
}
}
But (Ajax.BeginForm("Add", "Login")
does not make reference with controller event Please help, sorry for my bad english have a nice Day and thank you.

Loading partialView through ajax not working

i am trying to show order Summary through partial View and ajax.Request is going to server but my action method of Showsummary never hits. i want to summary of order through partial view.
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
var p = model.Packages.SelectMany(x => x.Packages).Select(y => new OrderPackagesViewModel()
{
PkgName = y.PkgName,
pkg_Id = y.id,
Ser_Id = y.Ser_Id,
Quantity = y.Quantity,
price = (y.TotalPrice - (y.DiscountPercent / 100 * y.TotalPrice)) * y.Quantity
}).ToList();
model.OrderPackages = p;
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
My Ajax
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Order/Showsummary",
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
$('#page_2').hide();
$('#page_3').show();
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
})
//Html Code
<div id="page_1">
<input asp-for="cus_name" placeholder="First Name" >
<input asp-for="Email" placeholder="Email" >
<select asp-for="Country" class="ui search dropdown">
<option value="">Select Country</option>
<option value="AF">Afghanistan</option>
<option value="AX">Ă…land Islands</option>
</select>
<input asp-for="cus_phone" placeholder="Phone Number"/>
<select asp-for="FirstPreferences" class="custom-select mr-sm-2"
asp-items="#(newSelectList(Preferences))">
<option value="">Select</option>
</select>
<select asp-for="FirstPreferedTimeStart" class="menu">
<option value="">HH:MM</option>
<option value="00:00:00">00:00</option>
<option value="01:00:00">01:00</option>
</select>
<textarea asp-for="Message" class="form-control"> </textarea>
</div>
//Page2 details of packages available. It is list of GroupByServices which contain fields ser_id Ser_Name and List of ServicePackages.
<div id="page_2" style="display:none">
<div>
<h1 id="heading">Choose a Package!</h1>
</div>
<div class="buttons">
#foreach (var services in Model.Packages)
{
<a href="#service_#services.Ser_Id"><div class="logo-p">
<h2>#services.Ser_Name</h2></div></a>
}
</div>
<!-- packages -->
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="packages" id="service_#Model.Packages[i].Ser_Id">
<h1 id="custom-website-design">
#Model.Packages[i].Ser_Name
</h1>
<div class="packs-content">
#for (int j = 0; j < Model.Packages[i].Packages.Count(); j++)
{
<div class="pack1">
<div class="pack-price">
<div>
<input asp-for="#Model.Packages[i].Packages[j].id" hidden />
<input asp-for="#Model.Packages[i].Packages[j].PkgName" hidden />
<input asp-for="#Model.Packages[i].Packages[j].Ser_Id" hidden />
<input asp-for="#Model.Packages[i].Packages[j].Ser_Name" hidden />
<h1>#Model.Packages[i].Packages[j].PkgName</h1>
<p>#Model.Packages[i].Packages[j].Ser_Name PACKAGE</p>
</div>
<p>$#Model.Packages[i].Packages[j].TotalPrice</p>
<input asp-for="#Model.Packages[i].Packages[j].TotalPrice" hidden />
</div>
<div class="pack-features">
<div class=""></div>
#foreach (var features in Model.Packages[i].Packages[j].Description)
{
<h2>#features</h2>
}
</div>
<div class="pack-order">
<div class="row-1">
#{
double discount = (Model.Packages[i].Packages[j].DiscountPercent / 100 * Model.Packages[i].Packages[j].TotalPrice);
double PriceAfterDiscount = Model.Packages[i].Packages[j].TotalPrice - discount;
}
<p>SPECIAL DISCOUNT</p>
<P>-$#discount</P>
</div>
<div class="row-2">
<p>FINAL PRICE FOR LIMITED TIME</p>
</div>
<div class="row-3">
<a asp-controller="Packages" asp-action="Detail" asp-route-id="#Model.Packages[i].Packages[j].id" target="_blank">view details</a>
<h1>$#PriceAfterDiscount</h1>
<input asp-for="#Model.Packages[i].Packages[j].DiscountPercent" hidden />
</div>
<div class="row-4">
<h4>Add To Buying List</h4>
<div class="input-group mb-3 order-btn-pack">
<div class="input-group-prepend">
<div class="input-group-text">
<input asp-for="#Model.Packages[i].Packages[j].is_selected" aria-label="Checkbox for following text input">
</div>
</div>
<input asp-for="#Model.Packages[i].Packages[j].Quantity" value="1" min="1" required placeholder="Quantity" class="form-control" aria-label="Text input with checkbox">
</div>
</div>
<div class="row-5">
<p>Discuss this offer with expert</p>
<div class="discuss">
<p>12345467889</p>
<p id="chat-btn_10">Live Chat</p>
</div>
</div>
</div>
</div>
}
<input asp-for="HoldPackage" hidden/>
</div>
</div>
}
<div>
<button type="button" class="btn btn-danger px-2 btn-lg" onclick="PageBack(this.parentElement.parentElement)">Back</button>
<button type="button" class="btn btn-danger px-2 btn-lg" id="summary">Summary!</button>
</div>
</div>
Edit!!!!
i have changed this line in ajax now it start hitting my controller action but still all form values are empty seems model binding is unable to recognize my fields
**const model= $("form").serialize()**
console.log(model); //data is there thats fine
and in ajax
data: { model },
my model have field called packages which is list of some fields and inside it there is one another list.
One thing is clear. $("form").serialize() is not working in my case its giving me 415 Unsupported Media Type client error response. I think problem is due to nested List
I have checked your code on my side with a simple OrderViewModel object, it works well. I suggest you could try to add '[FromBody]' in the action method, Like this:
....
Edit
According your description, it seems that you are using the Nested List and meet 415 error when using the [FromBody]. I have modified the sample code, in the action method, it's not using the [FromBody] attribute and in the JQuery Ajax method, there is no need to use the JSON.stringify method to change the JavaScript object. More detail information, please check the following code:
Model Class (Suppose the OrderViewModel contain a List):
public class OrderViewModel
{
public int OrderId { get; set; }
public string OrderName { get; set; }
public List<Package> Packages { get; set; }
}
public class Package
{
public int Pid { get; set; }
public string PackageTitle { get; set; }
}
Code in the Controller:
/// <summary>
/// //display the order
/// </summary>
/// <returns></returns>
public IActionResult ShowOrder()
{
OrderViewModel ovm = new OrderViewModel()
{
OrderId = 1001,
OrderName = "order 1",
Packages = new List<Package>()
{
new Package(){ Pid=101, PackageTitle="first Package"},
new Package(){ Pid=102, PackageTitle="second package"}
}
};
return View(ovm);
}
/// <summary>
/// JQuery ajax post method
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
ShowOrder.cshtml:
#model MVCSample.Models.OrderViewModel
#{
ViewData["Title"] = "ShowOrder";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
#*<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>*#
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Then the output as below:
Edit:
Besides, I also found that by using the above sample, if I just change the data: OrderViewModel to data: $("form.signup-form").serialize() (in the Ajax method), I could also get the OrderViewModel and the Packages in the action method.

Get object from controller to view using ajax in .net mvc core

Controller:
[HttpGet]
public IActionResult Edit(int id)
{
Teacher teacher = teacherService.GetTeacherById(id);
EditTeacherData(teacher);
return View();
}
public JsonResult EditTeacherData( Teacher teacher)
{
return Json(teacher);
}
Ajax:
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
View:
#model StudentTeacher.Models.TeacherViewModel
#{
ViewData["Title"] = "EditTeacher";
}
<h1>EditTeacher</h1>
<h4>Teacher</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form id="AddTeacherForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="TeacherId" id="TeacherId" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" id="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Designation" class="control-label"></label>
<input asp-for="Designation" class="form-control" id="Designation" />
<span asp-validation-for="Designation" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Education" class="control-label"></label>
<input asp-for="Education" class="form-control" id="Education" />
<span asp-validation-for="Education" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="JoiningDate" class="control-label"></label>
<input asp-for="JoiningDate" class="form-control" id="JoiningDate"/>
<span asp-validation-for="JoiningDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" id="Submit" />
</div>
</form>
</div>
</div>
teacherService is a service that retrieves data that match with id. But it return null object. When I use this EditTeacherData(teacher); ajax not return a null object But in debugger model show value takes this function. I just wanna get an object through ajax and show data in the field via ajax.
Obviously, there is no parameter passed in to the controller in your ajax, so Edit method will never receive the parameter passed in.
You can implement it with EF core. If you want to use ajax, you can refer to this.
You can also achieve it without ajax, it much easier, please refer to this.
You are not sending data from your ajax request. Please read this for clear understanding
$('#Submit').click(function(){
var formData = $('#AddTeacherForm').serialize();
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
data: formData,
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
})

How to check if a url belongs to a website that exists?

I am making a website where in a form, users can input a web page address. I was going to go with checking if the url is formatted correctly like an actual url which I think is the sloppy way and instead I want to check if url belongs to an actual website. Like, let's say user inputs www.pyrtyrmyrsyr.org, that is a valid address, but it doesn't lead to a website. Let's say user inputs www.python.org, that is both a valid address and leads to a website that exists.
And how can I check this validity before the form is sent and after input is given? Make the form's "send" button not clickable if url is not valid?
EDIT : Realized I didn't add any code of my view, apologize for that, also forgot to mention I use Bootstrap for View.
This is the form I use, what I am trying to do is use "Check" button, to check validity, by taking URL inside form-control with "id=url"
<div>
<div class="row">
<div class="col-md-12">
<h2 style="margin-left:20px; margin-top:10px">Add a Link</h2>
<form action="~/Link/Create" method="post">
<div class="form-group well clearfix" style="margin-left:20px; margin-right:20px; margin-top:20px">
<br />
<div class="row">
<label for="name" class="col-lg-2">URL:</label>
<div class="col-lg-9">
<input class="form-control" id="url" placeholder="URL" name="Address" /><br />
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-primary" id="checkurl">Check</button>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<label for="name">Interval:</label>
</div>
<!--<div class="col-lg-10">
<input class="form-control" placeholder="Interval to check (minutes)" name="Interval" /><br />
</div>-->
<div class="col-lg-5">
<select class="form-control" id="sel1">
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
<option>Weeks</option>
<option>Months</option>
</select>
</div>
<div class="col-lg-5">
<select class="form-control" id="sel2">
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
<option>Weeks</option>
<option>Months</option>
</select>
</div>
</div>
<div class="row">
<button class="btn btn-success pull-right" type="submit" style="width:200px; margin-right:15px">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
As far as I searched so far, connection to another domain/website is not possible using Javascript or anything similar so I need a server-side language, so I need to take this url, send it to control and return a true/false value after checking connection.
You can use Remote Validation in Asp.NET MVC. Let you have following property in your model.
public string URL {get; set;}
Add Remote attribute to your property like
[Remote("YourAction", "YourController", HttpMethod = "GET", ErrorMessage = "URL is not valid.")]
public string URL {get; set;}
Now write the following code in your specified action of the controller.
public class YourController : Controller
{
[AllowAnonymous]
public ActionResult YourAction(string URL)
{
try
{
//Check here by hitting your URL using HTTPClient or WebClient that it is returning something or not.
WebClient wc = new WebClient();
string HTMLSource = wc.DownloadString(URL);
return Json(true, JsonRequestBehavior.AllowGet); //Return true if it is valid.
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet); //Return false if it is not vald.
}
}
}
You must have to add following configurations in your web.config
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Your code on view will be like
#Html.EditorFor(model => model.URL, new { type = "url", #class = "form-control", placeholder = "URL" } })
#Html.ValidationMessageFor(model => model.URL, "", new { #class = "text-danger" })
Solved it:
Added a bool to my model:
public bool Valid { get; set; }
Changed my view a little:
<div class="row">
<label for="name" class="col-lg-2">URL:</label>
<div class="col-lg-9">
<input class="form-control" id="url" placeholder="URL" name="Address" /><br />
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-primary pull-right" id="checkurl">Check</button>
</div>
<input type="hidden" name="Valid" id="Validity"/>
</div>
Used the following codes, one for checking validity, other to reset form being usable if input is changed
$('#checkurl').click(function () {
var address = $('#url').val();
$.ajax({
url: "/Control/CheckUrl",
type: "POST",
data: JSON.stringify({ url: address }),
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result) {
document.getElementById("Validity").value = true;
document.getElementById("saveBut").disabled = false;
}
else {
document.getElementById("Validity").value = false;
document.getElementById("saveBut").disabled = true;
}
},
async: true,
processData: false
});
});
$('#url').change(function ()
{
if (document.getElementById("saveBut").disabled == false)
{
document.getElementById("Validity").value = false;
document.getElementById("saveBut").disabled = true;
}
});
Ajax code there leads to a controller function that reformats URL a bit and checks validity:
public ActionResult CheckUrl(string url)
{
try
{
if (String.IsNullOrEmpty(url)) return Json(false, JsonRequestBehavior.AllowGet); ;
if (url.Equals("about:blank")) return Json(false, JsonRequestBehavior.AllowGet); ;
if (!url.StartsWith("http://") && !url.StartsWith("https://"))
{
url = "http://" + url;
}
WebClient wc = new WebClient();
string HTMLSource = wc.DownloadString(url);
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
It works flawlessly and as desired.

Working on view with two forms on one controller in mvc 5

I have one drop down box. Based on the selected item of dropdownbox i want to generate form below on same view, Please find the code below.
[HttpGet]
public ActionResult BindDropDown()
{
ViewBag.doctype = new SelectList(db.DocTypeMasters, "Id", "DocTypeName");
return View();
}
[HttpPost]
public ActionResult BindDropDown(string DocType)
{
String Doc = DocType.Trim();
return View();
}
this is my view code
#model C3CardKYC.Models.DocTypeMaster
#{
ViewBag.Title = "BindDropDown";
}
<h2>BindDropDown</h2>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#MyIdAndName').change(function () {
var DocType = $("#MyIdAndName option:selected").text();
alert(DocType);
$.ajax({
url: '#Url.Action("BindDropDown", "Document")',
type: 'POST',
data: { DocType: DocType },
success: function (result) {
alert('success')
}
})
});
});
</script>
<fieldset>
<legend>DocTypeMaster</legend>
#*Select Document Type: #Html.DropDownList("doctype", "Select");*#
#Html.DropDownList("MyIdAndName", ViewBag.doctype as SelectList, " -- Select Document Type -- ")
</fieldset>
<p id="hi">
#Html.ActionLink("Back to List", "Index")
</p>
<div id="hi">
#using (Html.BeginForm("BindDropDown", "Document", FormMethod.Post, new { id = "submitForm" }))
{
<fieldset>
<ol>
<li>
#Html.LabelFor(Model => Model.DocTypeName)
#Html.TextBoxFor(Model => Model.DocTypeName, new { maxlength = 50 })
#Html.ValidationMessageFor(Model => Model.DocTypeName)
</li>
</ol> <button type="submit" id="btnSave" name="Command" value="Save">Save</button>
<button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
<button type="submit" id="btnCancel" name="Command" value="Cancel" onclick="$('#submitForm').submit()">Cancel (Server Side)</button>
</fieldset>
}
</div>
When i run this below error is coming.
There is no ViewData item of type 'IEnumerable' that has the key 'MyIdAndName'.
and if i select the item frm dropdown then only below form should appear. Please suggest

Resources