view in mvc can not render html for the second time - c#

when I try to render HTML in view for the second time the HTML not change and nothing happens it still as it aims calling the same view two times when the modal is empty and when I fill modal with data and then try to render it
this is the view
<section class="col-12 m-b-60">
<h2 class="m-b-20">Deduction</h2>
<form class="form-inline">
<div class="row">
<div class="col-6">
<div class="input-group">
<label class="input-text">
<span class="label">Employee ID</span>
<input type="text" placeholder="Employee ID ..."id="employeid">
</label>
<a class="btn btn-default" onclick="veiwemployee()">
Get
</a>
</div>
</div>
<div class="col-6">
<div class="input-group">
</div>
</div>
</div>
</form>
</section>
<section class="col-12 m-b-20">
`#if (Model != null)`
{
#await Html.PartialAsync("/Views/Home/View.cshtml", Model);
}
</section>
The action
public IActionResult EmployeeDeduction(int employeeID = 0)
{
Deduction deduction = new Deduction() ;
if (employeeID == 0) { }
else
{
ModelState.Clear();
deduction = _conn.GetEmployeByEmployeeID(employeeID);
}
return View("/Views/view.cshtml",deduction);
}
The Js function
function veiwemployee() {
if ($("#employeid").val() == "") {
$("#employeid").style.borderColor = "red";
}
else {
$.ajax({
type: 'POST',
url: '/Home/EmployeeDeduction?employeeID=' + $("#employeid").val(),
async: false,
dataType: 'json',
success: function (resp) {
}
});
}
}

this tag does not have closing.
<input type="text" placeholder="Employee ID ..." id="employeid">
"/" missing

Related

How to trigger Model Validation inside modal? .NET 5

i Have problem when i try the model validation by trying to fill the form by false.
And when i try to submit with the wrong value (not valid by model validator) it redirects to the page (without model).
Here's the screenshot :
Customer Index
redirect to Customer Create Page when i submit
Here's the code
CONTROLLER
//POST CREATE
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Models.Customer obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
//GET DELETE
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var obj = _db.Customers.Find(id);
if (obj == null)
{
return NotFound();
}
return PartialView(obj);
}
Model
public class Customer
{
[Key]
public int Id { get; set; }
[DisplayName("Nama Customer")]
[Required]
[MaxLength(81, ErrorMessage ="Tidak boleh melebihi 81 Karakter")]
public string Nama { get; set; }
public string Alamat { get; set; }
[Phone]
[Required]
public string Telp { get; set; }
}
Index.HTML Button Create
<button id="btnAddCustomer" class="btn btn-primary">Tambah Customer</button>
JS
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
CREATE CSHTML
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row">
<div class="col-4">
</div>
<div class="col-4">
<h2 class="text-black-50 pl-3">Add Customer</h2>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
#*validasi form*#
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-6">
</div>
<div class="col-6">
</div>
<div class="col-6">
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
<input type="submit" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
Thank you (:
And when i try to submit with the wrong value (not valid by model
validator) it redirects to the page (without model).
You use return View(obj); when modelstate is not valid. So it will return view with model and the view name should be the action name(Create) if you do not specific view name. So this result is correct by using your code.
Here is a working demo:
Index.cshtml:
<button id="btnAddCustomer" class="btn btn-primary"> Tambah Customer</button>
<div class="modal fade" id="modalCustomer" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#section Scripts{
<script>
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
//$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
</script>
}
Create.cshtml:
#model Customer
#{
Layout = null; //be sure add this...
}
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row"><div class="col-4"></div><div class="col-4"><h2 class="text-black-50 pl-3">Add Customer</h2></div><div class="col-4"></div></div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row"><div class="col-6"></div><div class="col-6"></div><div class="col-6"></div></div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
#*change here..........*#
<input type="button" id="btn" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
JS in Create.cshtml:
<script>
$(document).on('click', '#modalCustomer #btn', function () {
var options = {};
options.type = "POST";
options.url = "/Customer/create";
options.dataType = "JSON";
options.cache = false;
options.async = true;
options.data = $("form").serialize();
options.success = function (data) {
//do your stuff...
$('#modalCustomer').modal('hide');
//if you don't want to stay in Index
//add the following code..
// window.location.href = "/home/privacy";
};
options.error = function (res) {
$('#modalBody').html(res.responseText);
};
$.ajax(options);
});
</script>
Update:
If modelstate is invalid, it will get into options.error and display the error message in modal. If modelstate is valid, it will get into options.success, you could redirect by using window.location.href or hide the modal by $('#modalCustomer').modal('hide');, just do your stuff.
Backend code should be like below:
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Customers obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return Json(new { success = true }); //change this...
}
return View(obj);
}

How to use Ajax with MVC, MySQL and Entity Framework, no razor pages

I messed up last time so let us see if I can get it right this time. I am trying to figure out first where to put the Ajax at and how to put it in my controller. First my controller looks like this
[update] I am trying to make my messages popup without refreshing. It works without ajax I just need someone to explain where to put in the ajax and how to interact with it. I don't want a alert I want the messages to update in that one section. In the answer I tried to figure out what he was saying yet this is what i got when I clicked send
{"htmlMsg":"data addes to database successfull","htmlBody":"","success":true}
I don't want to see this I want it to just update the message section. My goal has not been met yet so I am completely confused.
Underneath you see the image of it working before I added the ajax recommended. Now it sends me to that a different page.
[HttpGet("wall")]
public IActionResult Wall(int userID)
{
ViewBag.User = GetUserInDB();
// if(ViewBag.User == null)
// {
// return RedirectToAction("Index");
// }
ViewBag.Messages = DBContext.Messages
.Include(i => i.Messenger)
.ToList();
return View();
}
[HttpPost("NewMessage/Add")]
public IActionResult NewMessage( Message newMessage)
{
User userInDB = GetUserInDB();
Message thisMessage = newMessage;
System.Console.WriteLine(newMessage.TheMessage);
thisMessage.UserID = userInDB.UserID;
DBContext.Messages.Add(thisMessage);
DBContext.SaveChanges();
return RedirectToAction("Wall");
}
What I am trying to do is change the outline to it because I know I need to do something like this
[HttpPost("NewMessage/Add")]
public JsonResult NewMessage( Message newMessage)
{
User userInDB = GetUserInDB();
Message thisMessage = newMessage;
thisMessage.UserID = userInDB.UserID;
DBContext.Messages.Add(thisMessage);
DBContext.SaveChanges();
return Json(thisMessage);
}
Is this correct? Or do I need to do something else?
Secondly I truly can't figure out the second part on the HTML section. Originally I had
#model Message
<div class="jumbotron p-2 m-3">
<img class="logo" src="/images/melysLogo.jpg" alt="Logo Image">
#if (ViewBag.User == null)
{
<a class="mr-2" href="/LoginOrRegister">Login Or Register</a>
}
else
{
Logout <span>|</span>
Add Recipe<span>|</span>
<a class="mr-2" href="/">Dashboard</a>
}
<span style="font-size:x-large;">Melly's Underground Cuisine</span>
</div>
<style>
.messageboard {
width: 97%;
height: 600px;
background-color: black;
color: white;
}
</style>
<div class="messageboard m-3 p-3 rounded">
<div class="m-3 p-3 sizeclass">
#foreach (Message message in ViewBag.Messages)
{
<div class="d-flex justify-content-around m-3 p-3 ">
<div class="p-2 rounded largeLabel border">#message.TheMessage </div>
<div class="p-2 rounded smallLabel border d-flex justify-content-center align-items-center">
#message.Messenger.FirstName
</div>
</div>
}
</div>
</div>
<footer class="m-4">
#if (ViewBag.User != null)
{
<form asp-action="NewMessage" asp-controller="Home" a method="post">
<input class="form-control-lg inputLabel m-1 " asp-for="TheMessage">
<button class="btn btn-outline-primary btn-warning m-2" type="submit">Send</button>
</form>
}
</footer>
I have tried but don't understand what goes in the success section. I also don't know what class or should i make name or id up for the message itself in the data I tried this but am still lost
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "/Home/NewMessage",
data: { "name": $(".messageboard").val() }, //I am also guessing the class is probably wrong as well
success: function (response) {
//what do I put here is what I am confused about as well
},
failure: function (response) {
console.log(response.failure)
},
error: function (response) {
console.log(response.error);
}
});
});
});
</script>
I would love to also know if using vs code is not worth it for c# and .net core thank you so much sorry about my last question. I didn't follow the guidelines properly
1-Replace this code with your view code
#model Message
<div class="jumbotron p-2 m-3">
<img class="logo" src="/images/melysLogo.jpg" alt="Logo Image">
#if (ViewBag.User == null)
{
<a class="mr-2" href="/LoginOrRegister">Login Or Register</a>
}
else
{
Logout <span>|</span>
Add Recipe<span>|</span>
<a class="mr-2" href="/">Dashboard</a>
}
<span style="font-size:x-large;">Melly's Underground Cuisine</span>
</div>
<style>
.messageboard {
width: 97%;
height: 600px;
background-color: black;
color: white;
}
</style>
<div class="messageboard m-3 p-3 rounded">
<div class="m-3 p-3 sizeclass">
#foreach (Message message in ViewBag.Messages)
{
<div class="d-flex justify-content-around m-3 p-3 ">
<div class="p-2 rounded largeLabel border">#message.TheMessage </div>
<div class="p-2 rounded smallLabel border d-flex justify-content-center align-items-center">
#message.Messenger.FirstName
</div>
</div>
}
</div>
</div>
<footer id="myFooter" class="m-4">
#if (ViewBag.User != null)
{
<form name="myForm" asp-action="NewMessage" asp-controller="Home" a method="post">
<input class="form-control-lg inputLabel m-1 " asp-for="TheMessage">
<button class="btn btn-outline-primary btn-warning m-2" type="submit">Send</button>
</form>
}
</footer>
<script>
$("#myform").submit( function () {
e.preventDefault(); //prevent default form submit
$.ajax({
type: "POST",
data : $("#myForm").serialize(),
cache: false,
url: "/Home/NewMessage",
success: function (result) {
//what do I put here is what I am confused about as well
if(result.Succeess)
{
//do youy want work if success....
}
else
{
//do youy want work if failed....
}
},
error: function (result) {
console.log(result.error);
});
return false;
});
</script>
2-Create a class in your project called JsonData
public class JsonData
{
public string HtmlMsg { get; set; }
public string HtmlBody { get; set; }
public bool Success { get; set; }
}
and your NewMessage Action in controller change to:
[HttpPost("NewMessage/Add")]
public JsonResult NewMessage(Message newMessage)
{
try
{
User userInDB = GetUserInDB();
Message thisMessage = newMessage;
thisMessage.UserID = userInDB.UserID;
DBContext.Messages.Add(thisMessage);
DBContext.SaveChanges();
return Json(new JsonData()
{
HtmlMsg = "data add to database successfull",
HtmlBody = "",
Success = true,
});
}
catch
{
return Json(new JsonData()
{
HtmlMsg = "data add to database failed",
HtmlBody = "",
Success = false,
});
}
}
So I got it to work thank you a lot but this is what I did
// wall html
#model Message
<div id="theDamMessages">
<partial name="MessagePartial" />
</div>
<footer class="m-4">
#if (ViewBag.User != null)
{
<form id="myform" method="POST">
<input id="inputey" class="form-control-lg inputLabel m-1 " asp-for="TheMessage">
<button class="btn btn-outline-primary btn-warning m-2" type="submit">Send</button>
</form>
}
</footer>
<div>
<script>
$("#myform").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
data: $("#myform").serialize(),
cache: false,
url: "/AddMessage",
success: function (result) {
console.log(result)
$("#theDamMessages").html(result);
$("#myform")[0].reset();
var theheight = $(".messageboard")[0].scrollHeight;
$(".messageboard").scrollTop(theheight);
},
error: function (result) {
console.log(result);
}
})
});
</script>
</div>
[HttpPost("AddMessage")]
public IActionResult AddMessage(Message newMessage)
{
User userInDB = GetUserInDB();
Message thisMessage = newMessage;
System.Console.WriteLine(newMessage.TheMessage);
thisMessage.UserID = userInDB.UserID;
DBContext.Messages.Add(thisMessage);
DBContext.SaveChanges();
ViewBag.Messages = DBContext.Messages
.Include(i => i.Messenger)
.ToList();
return PartialView("MessagePartial");
}
<div class="messageboard m-3 p-3 rounded">
<div class="m-3 p-3 sizeclass">
#foreach (Message message in ViewBag.Messages)
{
<div class="d-flex justify-content-around m-3 p-3 ">
<div class="p-2 rounded largeLabel border">#message.TheMessage </div>
<div class="p-2 rounded smallLabel border d-flex justify-content-center align-items-center">
#message.Messenger.FirstName
</div>
</div>
}
</div>
</div>

asp.net mvc controller return json List<T> unknown error

I'm simply trying to send back the List collection from the controller to the ajax function as JSON string, and for it to be recieved so i can manipulate the view.
I've done this before with collections but i can't see what the issue is, i get the required json as per the image link at the bottom. However i see no error apart from "json response - undefined" in the other link for the browser console when debugging.
I've already tried:
1. creating a new SalaryCalculator object of data (which posts back okay)
2. also created an anonymous type (which again posts back fine)
Controller method
[HttpPost]
public ActionResult GetSalaryCalculation(List<SalaryCalculator> form)
{
foreach (var entry in form)
{
entry.Tax = TaxCalculation(entry.Salary);
entry.MonthlyNet = MonthlyCalculation(entry.Salary, entry.Tax);
entry.WeeklyNet = WeeklyCalculation(entry.MonthlyNet);
entry.HourlyRate = HourlyCalculation(entry.WeeklyNet, entry.WeeklyHours);
if (entry.OverTimeHours > 0)
{
entry.OvertimeTotal = OvertimeCalculation(entry.OverTimeHours, entry.HourlyRate);
}
entry.OvertimeSalaryTotal = TotalCombinedCalculation(entry.MonthlyNet, entry.OvertimeTotal);
entry.TaxCode = "tax";
if (entry.Pension > 0)
{
entry.Pension = PensionCalculation(entry.OvertimeSalaryTotal, entry.Pension);
}
if (entry.StudentLoan > 0)
{
entry.StudentLoan = StudentLoanCalculation(entry.OvertimeSalaryTotal, entry.StudentLoan);
}
}
return Json(form, JsonRequestBehavior.AllowGet);
//return Content(JsonConvert.SerializeObject(form));
}
AJAX call
initialise: function () {
$("#calculateAmount").on("click", function () {
var formData = [
{
Salary: $("#salaryAmount").val(),
WeeklyHours: $("#hoursWorked").val(),
StudentLoan: $("#studentValidation").val(),
Pension: $("#pensionValidation").val(),
OverTimeHours: $("#overtimeValidation").val()
}
];
//console.log(formDataArray);
Ajax.fn.ajaxPost("GetSalaryCalculation",
function (jsonSuccess) {
console.log(jsonSuccess);
},
function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
},
{ form: formData }
);
});
}
Processing AJAX
$.ajax({
type: "POST",
url: "/Home/" + sFunction,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: data === null ? null : JSON.stringify(data),
success: function (response, status, jqXhr) {
if (typeof response.d !== "undefined") {
onSuccess(response.d, status, jqXhr, passThroughData);
} else {
onSuccess(response, status, jqXhr, passThroughData);
}
},
error: function (jqXhr, status, errorName) {
// Handle generic errors if they exist, otherwise forward to error handler
if (jqXhr.status === 401) {
// Unauthorised. Force a refresh
window.location.href = window.location.href;
return;
}
else if (status === "timeout") {
// Function call timeout
}
onError(jqXhr, status, errorName, passThroughData);
},
timeout: iTimeoutMillis,
});
Index View
<form id="calculateForm">
<div class="form-group row">
<div class="col-sm-10">
<input type="text" class="form-control" id="salaryAmount" placeholder="Salary amount £" aria-label="Salary Amount" aria-describedby="salary Amount" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="text" class="form-control" id="hoursWorked" placeholder="Weekly hours worked" aria-label="Hours Worked" aria-describedby="Hours Worked" required>
</div>
</div>
<div class="form-group row collapse" id="studentLoan">
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Student loan £" aria-label="Student Loan" id="studentValidation" aria-describedby="Student Loan">
</div>
</div>
<div class="form-group row collapse" id="pensionPayment">
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Pension Payment £" aria-label="Pension Payment" id="pensionValidation" aria-describedby="Pension Payment">
</div>
</div>
<div class="form-group row collapse" id="overtimeAdjustment">
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Overtime hours" aria-label="Overtime Amount" id="overtimeValidation" aria-describedby="Overtime Amount">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="checkbox" data-toggle="collapse" href="#studentLoan" id="studentCheck">
<label class="form-check-label" for="studentLoan">
Student loan repayment
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="checkbox" data-toggle="collapse" href="#pensionPayment" id="pensionCheck">
<label class="form-check-label" for="pensionPayment">
Pension payment
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="checkbox" data-toggle="collapse" href="#overtimeAdjustment" id="overtimeCheck">
<label class="form-check-label" for="overtimeAdjustment">
Overtime hours
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-outline-primary" id="calculateAmount">Calculate</button>
</div>
</div>
</form>
Browser console display :
Controller action displaying json :
controller debugging with form data recieved from ajax
I have figured out the problem, it seems it was to do with the way JavaScript handles decimal values (IE it doesn't natively) combined with the way data was being entered from the input forms.
Explicitly converting the user input in Javascript using
parseFloat().toFixed()
Then passing the data to the controller via AJAX call seems to fix the issue but i am going to look into finding a way to calculate the data in another way.

How to call user control method using jQuery AJAX in Asp.Net

Here is the acsx page.
I have two drop down in Bootstrap modal (State and City).
Based on the state selection, City dropdown should populate option.
I have created two methods in code behind for state FillStatedata() and for city getCitydata().
I need to call getCitydata() method on state selection change using jQuery AJAX and then bind the city data with city drop down.
I am getting Statename on state change but not able to executive getCitydata() method using statename as parameter.
Why?
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Registeration.ascx.cs" Inherits="WebApplication1.UserControl.Registeration" %>
<%# Import Namespace = "System.Web.Security" %>
<script src="~/scripts/jquery-1.10.2.js"></script>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<!--jquery start here-->
<script>
$(document).ready(function () {
var getSelState;
$("#State").change(function () {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: alert("{'Statename':'" + $('#State').val() + "'}"), //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) { //handle the callback to handle response
//request was successful. so Retrieve the values in the response.
}
})
});
});
</script>
<input type="hidden" id="myhiddenField" name="myhiddenField" value="" ClientIDMode="Static" runat="server" />
<div class="form-horizontal" role="form" runat="server">
New User?
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Register</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="full-name" class="col-sm-2 control-label">FullName:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="full-name">
</div>
</div>
<div class="form-group">
<label for="User-Name" class="col-sm-2 control-label">Username:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="User-Name">
</div>
</div>
<div class="form-group">
<label for="Create-Password" class="col-sm-2 control-label">Create Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Create-Password">
</div>
</div>
<div class="form-group">
<label for="confirm-Password" class="col-sm-2 control-label">Confirm Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Confirm-Password">
</div>
</div>
<div class="form-group">
<label for="Mobile-Number" class="col-sm-2 control-label">Mobile No:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Mobile-Number">
</div>
</div>
<div class="form-group">
<label for="State" class="col-sm-2 control-label">State:</label>
<div class="col-sm-10">
<select class="form-control" id="State" runat="server" ClientIDMode="Static">
</select>
</div>
</div>
<div class="form-group">
<label for="City" class="col-sm-2 control-label">City:</label>
<div class="col-lg-10">
<select class="form-control" id="City" runat="server" DataTextField="Cityname"
DataValueField="Cityname"></select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-primary">Cancel</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
First things first.
just use one library either min for prod or non min for dev.
data:{} should have to be an object or string value.
use one of it:
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var getSelState;
$("#State").change(function() {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: "{'Statename':'" + this.value + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) { //handle the callback to handle response
console.log(msg);
}
});
});
});
</script>
function getCitydata()(obj) {
var ddlcity = document.getElementById('<%= ddlcity.ClientID %>');
ddlcity.innerHTML = '';
$.support.cors = true;
var serviceUrl = '/ashx/map/Address.ashx';
if (serviceUrl.indexOf('?') > -1)
serviceUrl += '&jsonp='
else
serviceUrl += '?jsonp='
serviceUrl += '?&type=1&StateId=';
serviceUrl += document.getElementById('<%= ddlState.ClientID%>').value;
$.ajax({
type: 'GET',
crossDomain: true,
async: false,
contentType: 'application/json; charset = utf-8',
url: serviceUrl,
data: '{}',
dataType: 'jsonp',
success: function (data) {
if (data != null && data.length > 0) {
$.map(data, function (item, index) {
var newListItem = document.createElement('option');
newListItem.text = item.City;
newListItem.value = item.CityId;
ddlcity.options.add(newListItem);
});
}
},
error: function (error) {
alert('error ' + error);
}
});
} // getCitydata()
To use this function you have to create one ashx file eg. Address.ashx file which consist method for getting the data from database

Can't see my Controller object in my MVC 5 View

I'm new to MVC, and I'm writing my first App in this technology.
i'm trying to return an Object to my view from the controller, but I can't see it in the view, hear is my Controller code:
`
public ActionResult Create(int id)
{
AddAffiliatModel serverUsersModel = new AddAffiliatModel();
ObjectResult<getServerUsers_Result> serverUsers = serverUsersModel.getSUsers();
List<getServerUsers_Result> users = serverUsers.ToList();
return View(users[0]);
}`
And here is my View code:
#model MVC_5_Skeleton1.Models.getServerUsers_Result
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>getUsers</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="~/JS/AddAffiliate.js"></script>
<style>
.txtW {
max-width: 300px;
}
.txtAH {
height: 200PX;
}
</style>
<script type="text/javascript">
//**************************************************************************
//** Jquery Ready function hooks the buttons click events *
//**************************************************************************
$(document).ready(function () {
$(document).on('click', 'button', function (e) {
buttonId = $(this).attr("id");
switch (buttonId) {
case "submit":
Validate();
clearFields();
break;
case "cancel":
break;
default:
break;
}
});
});
//**************************************************************************
//** Validate and send *
//**************************************************************************
function SendToServer() {
}
//**************************************************************************
//** Validate and send *
//**************************************************************************
function Validate() {
var errorMsg = "";
var postString = "";
var valid = 0;
var filter = /^([a-zA-Z0-9_\.\-])+\##(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if ($('#fullName').val().length > 2) {
var name = $('#fullName').val();
}
else {
errorMsg = 'Please enter name';
valid = 1;
}
if ($('#email').val().length > 5) {
var email = $('#email').val();
}
else {
errorMsg += 'Please valid email' + '/n';
valid = 1;
}
if ($('#skype').val().length > 3) {
var name = $('#skype').val();
}
else {
errorMsg = 'Please Skype name' + '/n';
valid = 1;
}
if ($('#Countries-leagues').val().length > 5) {
var cl = $('#Countries-leagues').val()
}
else {
errorMsg = 'Please enter Coverage' + '/n';
valid = 1;
}
if ($('#opinion').val().length > 5) {
var opinion = $('#opinion').val()
}
else {
errorMsg = 'Please enter Coverage' + '/n';
valid = 1;
}
if (valid == 0) {
send();
}
}
//**************************************************************************
//** Get desired length and string to chech *
//**************************************************************************
function Send() {
AffiliateData.pType = 'AddAffiliate';
AffiliateData.user[0].recomanderId = "1"
AffiliateData.user[0].userName = $('#fullName').val();
AffiliateData.user[0].email = $('#email').val();
AffiliateData.user[0].skype = $('#skype').val();
AffiliateData.user[0].covered = $('#Countries-leagues').val();
AffiliateData.user[0].opinion = $('#opinion').val();
if ($('#canConnect').is(":checked")) {
AffiliateData.user[0].canContact = "1";
}
else {
AffiliateData.user[0].canContact = "0";
}
if ($('#aware').is(":checked")) {
AffiliateData.user[0].aware = "1";
}
else {
AffiliateData.user[0].aware = "0";
}
$.ajax({
type: "POST",
processData: false,
url: "http://localhost/MVC%205%20Skeleton1/AddAffilate/Create/1",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ json: AffiliateData }),
// dataType: "json",
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
//**************************************************************************
//** Clean UI Fields *
//**************************************************************************
function clearFields() {
$('#fullName').val("");
$('#email').val("");
$('#skype').val("");
$('#email').val("");
$('#Countries-leagues').val("");
$('#opinion').val("");
$('input:checkbox').removeAttr('checked');
}
//********************* end of script block *********************
</script>
</head>
<body>
<h2>Create new Affilate</h2>
<fieldset>
<!-- Form Name -->
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="textinput">Candidate Name </label>
</div>
<div class="col-md-12">
<input id="fullName" name="textinput" type="text" placeholder="Candidate Name " class="form-control input-md txtW" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="email">Email</label>
</div>
<div class="col-md-12">
<input id="email" name="email" type="email" placeholder="Email" class="form-control input-md txtW" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="skype">Skype</label>
</div>
<div class="col-md-12">
<input id="skype" name="skype" type="text" placeholder="Skype" class="form-control input-md txtW" required="">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-12 control-label" for="Countries-leagues">Countries/leagues</label>
<div class="col-md-12">
<textarea class="form-control txtW txtAH" id="Countries-leagues" name="Countries-leagues" required=""></textarea>
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-12 control-label" for="opinion">Way are you recommending Him/Her</label>
<div class="col-md-4">
<textarea class="form-control txtW txtAH" id="opinion" name="opinion" required=""></textarea>
</div>
</div>
<!-- Multiple Checkboxes -->
<div class="form-group">
<label class="col-md-12 control-label" for="checkboxes"></label>
<div class="col-md-4">
<div class="checkbox">
<label for="checkboxes-0">
<input type="checkbox" name="checkboxes" id="canConnect" value="0">
Can we contact he/she?
</label>
</div>
<div class="checkbox">
<label for="checkboxes-1">
<input type="checkbox" name="checkboxes" id="aware" value="0">
Dose he/she knows will approach them?
</label>
</div>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-12 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-success">Submit</button>
<button id="cancel" name="cancel" class="btn btn-primary">Cancel</button>
</div>
</div>
</fieldset>
</body>
</html>
How can I get to my #model ?
Can I use the data in my Jquery code?
Thanks
You can access your model properties by using #Model.PropertyName.
Example:
<textarea class="form-control txtW txtAH" id="opinion" name="opinion" required="">#Model.opinion</textarea>
Edited: I saw on your question commens on how to access that information with jQuery.
If you follow the previous example, you can access it by simply
$("#opinion").val()

Categories

Resources