Validation in Partial view inside popup - javascript

I'm working in MVC and i have one scenario as follows:
I have a view called ManageResource where i il show the available resource's in grid and a button to add new resource. if i click on the add new resource button a popup il open with the partialview inside it, i have to display the validation result in popup itself when i click save with out entering any values and when i enter the required fields the values should be populated in the grid and the popup should be closed.`
"iam not getting validation result in popup, but can able to save data's"
following is my code:
Model-tblUser
public partial class tblUser
{
public int UID { get; set; }
[Required]
public int EmpID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public decimal Salary { get; set; }
}
View-ManageResource
function Create() {
BootstrapDialog.show({
title: "Add Resource",
message: $('<div id="CreatePopup"></div>').load('#Url.Action("Create", "Resource")')
});
return false;
}
<input type="button" id="AddNewCompany" onclick="Create()" class="push_button blue btn_width" value="Add New Resource" />
partial view- Create
function SaveResource() {
var obj = [];
var EmpID = $('#EmpID').val();
var FirstName = $('#FirstName').val();
var LastName = $('#LastName').val();
var Salary = $('#Salary').val();
if ($("#IsActive").attr('checked', true)) {
var IsActive = 1;
}
else {
var IsActive = 0
}
var newrecord = {
"EmpID": EmpID, "FirstName": FirstName, "LastName": LastName, "Salary": Salary,
};
var senddata = JSON.stringify(newrecord);
jQuery.ajax({
type: "POST",
url: '#Url.Action("Create", "Resource")',
data: JSON.stringify({ "data": senddata }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result == true) {
window.location.href = '#Url.Action("ManageResource", "Resource")';
} else {
$("#CreatePopup").html(result);
}
}
});
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false)
<div class="form-group">
#Html.LabelFor(model => model.EmpID, "Employee ID", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.EmpID)
#Html.ValidationMessageFor(model => model.EmpID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName,"First Name", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName,"Last Name", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-10">
<input type="button" id="CreateResource" onclick="SaveResource()" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Resource Controller
public PartialViewResult Create(string data)
{
JObject o = JObject.Parse(data);//parsing the json data
tblUser tbluser = new tblUser(); //creating instance for model tblUser
if ((string)o["EmpID"] != "" && (string)o["FirstName"] != "")// if all the required fields are present then add to db
{
db.tblUsers.Add(tbluser);//assign values here
tbluser.EmpID = (int)o["EmpID"];
tbluser.FirstName = (string)o["FirstName"];
tbluser.FirstName = (string)o["FirstName"];
tbluser.LastName = (string)o["LastName"];
tbluser.EmailID = (string)o["EmailID"];
tbluser.Password = (string)o["Password"];
tbluser.RoleID = (int)o["RoleID"];
tbluser.DeptID = (int)o["DeptID"];
tbluser.DesignationID = (int)o["DesignationID"];
tbluser.Salary = (int)o["Salary"];
tbluser.IsActive = (bool)o["IsActive"];
tbluser.CreatedBy = 121;
tbluser.CreatedDate = System.DateTime.Now;
tbluser.UpdatedBy = 121;
tbluser.UpdatedDate = System.DateTime.Now;
db.SaveChanges();
return RedirectToAction("ManageResource");//return to main view when saved
}
else
{
//return with validation summary to partialview popup
return PartialView(tbluser);
}
}

When you load a form using AJAX you need to tell jQuery unobtrusive validation to add the validation data- properties to the form elements. You need to add: $.validator.unobtrusive.parse('#YourFormSelector');
after the .load is completed.
function Create() {
BootstrapDialog.show({
title: "Add Resource",
message: $('<div id="CreatePopup"></div>').load('#Url.Action("Create","Resource")'
, function() {$.validator.unobtrusive.parse('#YourFormSelector');})
});
return false;
}

Related

Populate fields based on other fields ASP.NET Razor Pages

I know that this question might have been already on this site, but there are some different things in my approach because I use #Html.EditFor and #Html.DropDownList.
So I have a drop down list and when I choose the ID there I want to retrieve some information from the DB then populate some fields in the current form. I know that I should use JS but I don't know how.
View:
#model TestApp.Dtos.InsertDto
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="col-md-9">
#Html.DropDownListFor(model => model.Category, new SelectList(Model.ListOfCategory, "Text", "Text"), "-- Please select --", htmlAttributes: new { #class = "form-control"});
</div>
<div class="col-md-9">
#Html.EditFor(model => model.Car, new{htmlAttributes = new { #class = "form-control" }});
</div>
#*And then the form continues with other fields and after that the submit button *#
}
You can use ajax to get data from backend,and put the result data into somewhere you want.Here is a simple demo to get a selectListItem from backend and put it into a div.If you want to do something more complex,you need to share the structure of InsertDto,and explain clearly what kind of data you will get from db and explain what does populate some fields in the current form mean?
View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="col-md-9">
#Html.DropDownListFor(model => model.Category, new SelectList(Model.ListOfCategory, "Text", "Text"), "-- Please select --", htmlAttributes: new { #class = "form-control" ,#onchange = "getData()" })
</div>
<div id="dbdata">
</div>
}
js:
<script>
function getData() {
$.ajax({
type: "POST",
data: { Category: $("#Category").val() },
url: '/B/GetData',
}).done(function (result) {
$("#dbdata").html("the selected value is " + result.text);
});
}
</script>
Model:
public class InsertDto
{
public string Category { get; set; }
public List<SelectListItem> ListOfCategory { get; set; }
}
controller:
public IActionResult Index(string id)
{
InsertDto i = new InsertDto { ListOfCategory = new List<SelectListItem> { new SelectListItem { Text = "t1" }, new SelectListItem { Text = "t2" }, new SelectListItem { Text = "t3" } } };
return View(i);
}
public SelectListItem GetData(string Category)
{
return new SelectListItem { Text = Category, Value = Category + "value" };
}
result:

How to properly validate form using jquery Unobtrusive Validation?

I am trying to use jquery unobtrusive validation in my form, and no matter if the html inputs are empty or not, the validation message is always showing as soon as I open the page. The HTML is in a handlebars template. I am using HttpPost to retrieve data when loading the page.
My View:
<form id="submitForm" class="form">
<section id="conferenceContainer"></section>
<div id="saveBtnContainer">
<input type="submit" id="saveBtn" class="btn" value="Submit" />
<div id="lblCheckContainer">
<label id="lblCheck"></label>
</div>
</div>
</form>
<script type="text/x-handlebars-template" id="conferenceTemplate">
<div id="newConference">
<div class="form-group row">
#Html.LabelFor(x => x.ConferenceTitle,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.ConferenceTitle,
new { #id="confTitle", #class="form-control", #Value= "{{ConferenceTitle}}" })
#Html.ValidationMessageFor(x => x.ConferenceTitle, "*Enter a conference title*", new { #class="text-danger" })
</div>
<div class="form-group row">
#Html.LabelFor(x => x.EventDate,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.EventDate,
new { #id="confDate", #class="form-control", #Value="{{formatDate EventDate}}" })
#Html.ValidationMessageFor(x => x.EventDate, "*Enter the date of the conference*", new { #class="text-danger" })
</div>
<div class="form-group row">
#Html.LabelFor(x => x.RegFullPrice,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.RegFullPrice,
new { #id="confPrice", #class="form-control", #Value="{{RegFullPrice}}" })
#Html.ValidationMessageFor(x => x.RegFullPrice, "*Enter the price to register for conference*", new { #class="text-danger" })
</div>
<div class="form-group row">
#Html.LabelFor(x => x.PreRegEndDate,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.PreRegEndDate,
new { #id= "confPreRegDate", #class="form-control", #Value= "{{formatDate PreRegEndDate}}" })
#Html.ValidationMessageFor(x => x.PreRegEndDate, "*Enter the last day to pre-register for conference*", new { #class="text-danger" })
</div>
<div class="form-group row">
#Html.LabelFor(x => x.PreRegDiscount,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.PreRegDiscount,
new { #id= "confPreRegDiscount", #class="form-control", #Value= "{{PreRegDiscount}}" })
#Html.ValidationMessageFor(x => x.PreRegDiscount, "*Enter the discount for pre-registration*", new { #class = "text-danger" })
</div>
</div>
</script>
I am handling the submit input in .ready function where 'saveData()' is a method with the ajax call.
<script type="text/javascript">
var setup = new ConferenceSetup();
$(document).ready(function () {
setup.GetData();
$('#submitForm').submit(function () {
var confirmSave = confirm("Are you finished editing the Conference?");
if (confirmSave) {
setup.SaveData();
event.preventDefault();
} else {
event.preventDefault();
}
});
});
</script>
It seems I have the server side validation working but I cannot get the client side to act like I want.
My model:
[DisplayName("Conference Title")]
[Required]
public string ConferenceTitle { get; set; }
[DisplayName("Event Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd", ApplyFormatInEditMode = true)]
[Required]
public DateTime EventDate { get; set; }
[DisplayName("Registration Price")]
[Range(0, 999.99, ErrorMessage = "Price must be between $0 and $1,000")]
[Required]
public decimal RegFullPrice { get; set; }
[DisplayName("Pre-Registration End Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd", ApplyFormatInEditMode = true)]
[Required]
public DateTime PreRegEndDate { get; set; }
[DisplayName("Pre-Registration Discount")]
[Range(0, 999.99, ErrorMessage = "Discount must be between $0 and $1,000")]
[Required]
public decimal PreRegDiscount { get; set; }
My Controller:
[Authorize]
public class ConfSetupController : Controller
{
public ActionResult NewConf()
{
ConferenceModel model = new ConferenceModel();
return View(model);
}
This is what my page looks like, the validation messages never go away
Any help or suggestions is greatly appreciated!
To hide the validation on page load check if .field-validation-error and .validation-summary-valid css class "display" property is set to "none".

How to send client data to MVC controller for Login page?And save to database?

Login.cshtml
<script type="text/javascript">
function data() {
var n = document.getElementById("username").value;
var m = document.getElementById("password").value;
?
</script>
<button type="submit"class="btn-login" onClick="Data()">
Giriş Yap </button>
Account Controller
DBEntities dB = new DBEntities();
[HttpPost] (username) (password)
public ActionResult Login(string KullaniciAdi,string Sifre)
{
// Session[KullaniciAdi] = dB.Profil.Where(x => x.KullaniciAdi == KullaniciAdi && x.Sifre == Sifre).FirstOrDefault();
var session = (from p in dB.Profil
where p.KullaniciAdi == KullaniciAdi
select p).FirstOrDefault();
return View();
}
My OOP homework is this website and i want to create a login with sending password and username to controller and compare submitted data and the data in the database .Please help :)
You can send client data by using ajax request,
this is your inputs
<input id="username" type="text" />
<input id="password" type="password" />
<input id="loginbutton" onclick="UserLogin()" type="submit" value="Submit" />
Submit button bind with UserLogin js function.
here is the js function. we are sending ajax post request here to our controller
<script type="text/javascript">
function UserLogin() {
var n = document.getElementById("username").value;
var p = document.getElementById("password").value;
var postObj = JSON.stringify({
"username": n,
"password": p
});
$.ajax({
url: "/Home/Login", // endpoint
type: "POST",
data: postObj,
contentType: "application/json; charset=utf-8",
success: function (result) {
// success
},
error: function (errorData) { onError(errorData); }
});
}
</script>
And your controller should be like, you can implement login logic inside of the method.
[HttpPost]
public ActionResult Login(string username, string password)
{
// use your code loged in
return Json(true, JsonRequestBehavior.AllowGet);
}
First You Create a Class :
public class LoginModel
{
[Required(ErrorMessage = "User Name can not be empty!")]
public string LOGINID { get; set; }
[Required(ErrorMessage = "Password can not be empty!")]
public string LOGINPW { get; set; }
}
Then Your Controller Action Method do this:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//Here check the Login Id and Password
return View();
}
Now in view Write this. Now when you click the submit button a post call go to the Login Controller with given LOGINID and LOGINPW :
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<!-- login screen -->
<form action="#">
#Html.TextBoxFor(m => m.LOGINID, htmlAttributes: new { #class = "form-control", placeholder = "Login ID" })
#Html.ValidationMessageFor(model => model.LOGINID, "", new { #class = "text-danger", style = "float: left" })
#Html.PasswordFor(m => m.LOGINPW, htmlAttributes: new { #class = "form-control", placeholder = "Password" })
#Html.ValidationMessageFor(model => model.LOGINPW, "", new { #class = "text-danger", style = "float: left" })
<button type="submit" class="btn btn-primary" style="background: #2e6da4; color: #FFF;">Login</button>
</form>
}
#{
var actionURL = Url.Action("Action", "Controller",
FormMethod.Post, Request.Url.Scheme)
+ Request.Url.PathAndQuery;
}
#using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { #action = actionURL }))
{
<input type="text" name="username">
<input type="text" name="password">
<button type="submit"class="btn-login"></button>
}//Then use Request.Form[0] with the id to get the user name and password in the controller action.

ajax POST not passing back correct data

I am trying to pass back a json object back to my action in my device controller, this is then inserted into the database, however when I click the submit button on my form it seems to fire twice. Another problem is that my location field within the json object and pfID does not get sent back to the controller, the other fields get sent back properly. Here is my code:
$('#getDevice').unbind('click').bind('click', function (e) {
e.stopPropagation();
//anti forgery token
//get the form
var form = $('#addDeviceForm');
//from the form get the antiforgerytoken
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = 'Devices/PushIPForCollection';
//Before this we need to build the model from the input the user has given us
var device = {
deviceID: ' ',
ipAddress: $('#dIPAddress').val(),
deviceName: $('#dDeviceName').val(),
CreatedDate: ' ',
UpdatedDate: ' ',
CreatedBy: ' ',
UpdatedBy: ' ',
deviceSubGroupID: $('#dSubgroup option:selected').val(),
subgroup: " ",
companyID: ' ',
hidden: ' ',
pfID: $('#dpfID option:selected').val(),
pf: ' ',
location: JSON.stringify({
'region': $('#dRegion').val() == null ? ' ' : $('#dRegion').val(),
'country': $('#dCountry').val() == null ? ' ' : $('#dCountry').val(),
'city': $('#dCity').val() == null ? ' ' : $('#dCity').val(),
'building': $('#dBuilding').val() == null ? ' ' : $('#dBuilding').val(),
'room': $('#dRoom').val() == null ? ' ' : $('#dRoom').val(),
'rack': $('#dRack').val() == null ? ' ' : $('#dRack').val()
})
};
alert(device.pfID);
alert(device.location);
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
device: device
},
type: 'POST',
success: function (result) {
},
error: function (jqXHR, textStatus, errorThrown) {
alert("An error has occurred please contact us");
}
})
$('#add-device').modal('hide');
return false;
});
Where I alert my pfID it returns a string of "ba4475ef-0eed-441a-a77e-d733c288bf8e"
Here is my model:
public class Devices
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int deviceID { get; set; }
[Display(Name="IP Address:"), StringLength(50)]
public string ipAddress { get; set; }
[Display(Name = "DeviceName:"), StringLength(50)]
public string deviceName { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? UpdatedDate { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
[Display(Name="Add to subgroup:")]
public long? deviceSubGroupID { get; set; }
[ForeignKey("deviceSubGroupID")]
public DeviceSubGroup subgroup { get; set; }
public string companyID { get; set; }
public string hidden { get; set; }
public string pfID { get; set; }
[ForeignKey("pfID")]
public PfHealth.Pf pf { get; set; }
public string location { get; set; }
}
and here is my post method:
public ActionResult PushIPForCollection(Devices device)
{
//Before committing to the database we need to check if the device already exists
var checkIfDeviceExists = db.devices.Any(check => check.ipAddress == device.ipAddress);
if (!checkIfDeviceExists)
{
if (ModelState.IsValid)
{
var userID = User.Identity.GetUserId();
device.CreatedDate = DateTime.Now;
device.UpdatedDate = DateTime.Now;
device.CreatedBy = userID;
device.UpdatedBy = userID;
var subgroup = db.deviceSubGroups.Where(sub => sub.deviceSubID == device.deviceSubGroupID).FirstOrDefault();
device.communityString = subgroup.snmpCommunityString;
device.companyID = subgroup.companyID;
db.devices.Add(device);
db.SaveChanges();
}
}
//Can change this to get json in order to let to view know what message to display to the user.
return RedirectToAction("index");
}
and here is my form in the view:
<div class="modal fade" id="add-device" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="add-device-Label"><strong>ADD DEVICE</strong></h4><!--add depending on which panel you have clicked-->
</div>
<div class="modal-body" id="add-device-body">
<!--Depending on which panel insert content-->
#using (Html.BeginForm("PushIPForCollection", "Devices", FormMethod.Post, new { id = "addDeviceForm" }))
{
#Html.AntiForgeryToken()
<hr />
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-3">
#Html.LabelFor(m => m.device.ipAddress, new { #class = "col-md-2 control-label"})
</div>
<div class="col-md-9">
#Html.TextBoxFor(m => m.device.ipAddress, new { #class = "form-control", #id = "dIPAddress" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.LabelFor(m => m.device.deviceName, new { #class = "col-md-2 control-label" })
</div>
<div class="col-md-9">
#Html.TextBoxFor(m => m.device.deviceName, new { #class = "form-control", #id = "dDeviceName" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.LabelFor(m => m.device.deviceSubGroupID, new { #class = "col-md-2 control-label" })
</div>
<div class="col-md-9">
#Html.DropDownListFor(m => m.device.deviceSubGroupID, (IEnumerable<SelectListItem>)ViewBag.subGroups, "None", new { #id = "dSubgroup" })
#Html.ValidationMessageFor(m => m.device.deviceSubGroupID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Region:")
</div>
<div class="col-md-9">
#Html.TextBox("Region", "", new { #class = "form-control", #id = "dRegion" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Country:")
</div>
<div class="col-md-9">
#Html.TextBox("Country", "", new { #class = "form-control", #id = "dCountry" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("City:")
</div>
<div class="col-md-9">
#Html.TextBox("City", "", new { #class = "form-control", #id = "dCity" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Building:")
</div>
<div class="col-md-9">
#Html.TextBox("Building", "", new { #class = "form-control", #id = "dBuilding" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Room:")
</div>
<div class="col-md-9">
#Html.TextBox("Room", "", new { #class = "form-control", #id = "dRoom" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Rack:")
</div>
<div class="col-md-9">
#Html.TextBox("Rack", "", new { #class = "form-control", #id = "dRack" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.LabelFor(model=>model.device.pfID)
</div>
<div class="col-md-9">
#Html.DropDownListFor(m => m.device.pfID, (IEnumerable<SelectListItem>)ViewBag.pathfinders, "None", new { #id = "dpfID" })
#Html.ValidationMessageFor(m => m.device.pfID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="getDevice" type="submit" value="CreateGroups" data-loading-text="Loading..." class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
You do not need to create the javascript object manually, You may use jQuery serialize method to serialize the entire form and send it via ajax as long as the form field names matches with the param names/model property names in the HttpPost action method.
You may create a view model specific to the view.
public class CreateDeviceVm
{
public string DeviceId {set;get;}
public string IPAddress {set;get;}
public int DeviceSubGroupId {set;get;}
public List<SelectListItem> DeviceSubGroups {set;get;}
public string City {set;get;}
public string Room {set;get;}
//Add properties NEEDED FOR THE VIEW.
}
In your GET action, create an object of this view model, assign the DeviceSubGroups property and send to the view.
public ActionResult Create()
{
var vm = new CreateDeviceVm();
vm.DeviceSubGroups = db.DeviceSubGroups
.Select(s=> new SelectLisItem { Value=s.Id.ToString(),
Text = s.Name }).ToList();
return View(vm);
}
And in your view, which is strongly typed to the view model,
#model CreateDeviceVm
#using(Html.BeginForm())
{
<label>DeviceId</label>
#Html.TextBoxFor(s=>s.DeviceId)
<label>IP Address</label>
#Html.TextBoxFor(s=>s.IPAddress)
<label>Sub group</label>
#Html.DropDownListFor(s=>s.DeviceSubGroups,Model.DeviceSubGroups,"Select")
<label>City</label>
#Html.TextBoxFor(s=>s.City)
<label>Room</label>
#Html.TextBoxFor(s=>s.Room)
<input type="submit" id="btnSave" />
}
Now you can add some javascript to listen to the click event on the submit button, get a reference to the form, serialize it and send to the server using jQuery ajax.
$(function(){
$("#btnSave").click(function(e){
e.preventDefault();
var _f=$(this).closest("form");
$.post(_f.attr("action")._f.serialize(),function(res){
//check res and do something
});
});
});
And in your HttpPost action method,
[HttpPost]
public ActionResult Create(CreateDeviceVm model)
{
var exists= db.devices.Any(x=> x.ipAddress == model.ipAddress);
if (!exists)
{
var d= new Device();
d.IpAddress=model.IPAddress;
d.DeviceSubGroupId=model.DeviceSubGrouId;
//Map other properties as well.
db.Devices.Add(d);
db.SaveChanges();
return Json( new { status="success"});
}
return Json( new { status="failed"});
}

How to pass value to controller and partial view via JS

I'm trying to implement a system where the value within a text box is passed onto a partial view, where it will present the details corresponding to that value. So for instances if Job "1" was within the text box , the partial view will return the details of that job for the user to change etc. Any Ideas on how to pass the value to the controller then the partial view?
Job.js
$(document).ready(function () {
$('#qr-value').on('change', function () {
if ($('#qr-value').val() == 'Job 1') {
$("#second").show(1000);
}
});
});
CameraInfo (partial view)
model JobTracker.Models.Job
<h2>Edit and Confirm</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Job</legend>
#Html.HiddenFor(model => model.JobID)
<div class="editor-label">
#Html.LabelFor(model => model.OrderID, "Order")
</div>
<div class="editor-field">
#Html.DropDownList("OrderID", String.Empty)
#Html.ValidationMessageFor(model => model.OrderID)
</div><br />
<div class="editor-label">
#Html.LabelFor(model => model.LocationID, "Location")
</div>
<div class="editor-field">
#Html.DropDownList("LocationID", String.Empty)
#Html.ValidationMessageFor(model => model.LocationID)
</div><br />
<div class="editor-label">
#Html.LabelFor(model => model.HighPriority)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.HighPriority, new SelectList(
new[]
{
new { Value = "Yes", Text = "Yes" },
new { Value = "No", Text = "No" },
},
"Value",
"Text",
Model
))
#Html.ValidationMessageFor(model => model.HighPriority)
</div><br />
<div class="editor-label">
#Html.LabelFor(model => model.Comments)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Comments)
#Html.ValidationMessageFor(model => model.Comments)
</div><br />
<div class="editor-label">
#Html.LabelFor(model => model.Status)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Status, new SelectList(
new[]
{
new { Value = "In Progress", Text = "In Progress" },
new { Value = "Completed", Text = "Completed" },
new { Value = "Not Started", Text = "Not Started" },
new { Value = "Stopped", Text = "Stopped" },
},
"Value",
"Text",
Model
))
#Html.ValidationMessageFor(model => model.Status)
</div><br />
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to Home Page", "Index","Home")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Job Controller.cs
//
// GET: /Job/Edit/5
public ActionResult Edit(int id = 0)
{
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", job.LocationID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", job.OrderID);
return View(job);
}
//
// POST: /Job/Edit/5
[HttpPost]
public ActionResult Edit(Job job)
{
if (ModelState.IsValid)
{
db.Entry(job).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", job.LocationID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", job.OrderID);
return View(job);
}
<div id='Sample'></div>
if you want to load the partial view use ajax.
$(document).ready(function () {
$('#qr-value').on('change', function () {
$.ajax({
type: "Get",
url: '#Url.Action("Edit", "job")',
data: { id: $('#qr-value').val()},
success: function (response) {
$('#Sample').html(response);
},
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
alert("Some thing wrong..");
}
}
});
});
});
[HttpGet]
public ActionResult Edit(int id = 0)
{
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", job.LocationID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", job.OrderID);
return PartialView("Edit",job);
}
Hope this helps

Categories