AJAX Query Doesn't Call REST API Controller Method - javascript

I have a REST API controller configured as follows. On button click "PlayersRegistration", the update function in javascript is called prorperly. But the problem is that the PostPlayers Method in the DefaultController class never gets called using success: function(data) statement in update function. Instead when I check on the console in the browser by inspecting elements, i see Internal Server Error 500. I don't know what's wrong.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication2.Models
{
public class Default : ApiController
{
public string regID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string teamName { get; set; }
public DateTime dateOfBirth { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication2.Models;
using System.IO;
using System.Globalization;
using System.Windows.Forms;
namespace WebApplication2.Controllers
{
public class DefaultController : ApiController
{
List<Default>players = new List<Default>();
string path = Path.Combine(Directory.GetCurrentDirectory(), "\\players.txt");
public void readFile()
{
string line;
StreamReader file = new StreamReader(path);
string[] data;
players.Clear();
while ((line = file.ReadLine()) != null)
{
data = line.Split(',');
Default player = new Default();
player.regID = data[0];
player.firstName = data[1];
player.lastName = data[2];
player.teamName = data[3];
player.dateOfBirth = DateTime.ParseExact(data[4],
"yyyy-mm-dd", CultureInfo.InvariantCulture);
players.Add(player);
}
file.Close();
}
public IHttpActionResult PostPlayers(Default playerInfo)
{
readFile();
MessageBox.Show("5");
var player = players.FirstOrDefault((p) => p.regID == playerInfo.regID);
if (player != null)
{
players.Remove(player);
players.Add(playerInfo);
}
else
{
players.Add(playerInfo);
}
using (StreamWriter sw = File.CreateText(path))
{
for (int i = 0; i < players.Count(); i++)
sw.WriteLine(Players_Display(players[i]), Environment.NewLine);
sw.Close();
}
return Ok(players);
}
public string Players_Display(Default player)
{
string data = player.regID + "," + player.firstName + "," + player.lastName + "," + player.teamName + "," + player.dateOfBirth.ToString("yyyy-mm-dd").Substring(0,10);
return data;
}
}
}
THE HTML CODE is as follows
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<h2> All Players</h2>
<ul id="players"></ul>
</div>
<div>
<br />
<h2> Search or Delete </h2>
<select id="options_for_search_delete">
<option value="id">ID</option>
<option value="name">Name</option>
</select>
<input type="text" id="data" size="5" />
<input type="button" value="Search" onclick="search()" />
<input type="button" value="Delete" onclick="delet()" />
<br />
<p id="result_players" /><br>
<h2>Player Registration</h2>
<br />
<form>
<label for="id"> RegistrationID:</label><br>
<input type="text" id="regID" name="regID">
<br />
<label for="firstName">First Name:</label><br>
<input type="text" id="firstName" name="firstName">
<br />
<label for="lastName">Last Name:</label><br>
<input type="text" id="lastName" name="lastName">
<br />
<label for="teamName">Team Name:</label><br>
<input type="text" id="teamName" name="teamName">
<br />
<label for="dateofbirth">Date Of Birth:</label><br>
<input type="text" id="dateOfBirth" name="dateOfBirth">
<br />
<input type="button" id="post" value="Player Registration" onclick="update();" />
<p id="data_validation"></p>
</form>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/Default';
$(document).ready(function () {
$.ajax({
type: 'GET',
url: uri,
success: function (data) {
displayData(data);
}
})
})
function format(item) {
return item.regID + "," + item.firstName + " " + item.lastName + "," + item.teamName + "," + item.dateOfBirth.toString().substring(0, 10);
}
function displayData(data) {
$('ul').empty();
$.each(data, function (key, item) {
$('<li>', { text: format(item) }).appendTo($('#players'));
});
}
function update() {
$('#result_players').text("");
$('#data_validation').text("");
if ($('#regID').val() == "" || $('#firstName').val() == "" || $('#lastName').val() == "" || $('#teamName').val() == "" || $('#dateofbirth').val() == "") {
$('#data_validation').text("Input Boxes Cannot be Empty");
}
else {
$.ajax({
type: 'POST',
url: uri,
data: String($('form').serialize()),
success: function (data) {
displayData(data);
},
error: function (jqXHR, textStatus, err) {
alert(err);
}
})
}
}
</script>
</body>
</html>

"500 Internal Server Error" means "The server encountered an unexpected condition which prevented it from fulfilling the request."
So, your javascript could be quite ok, but the server side failed to execute the request and the succes callback never gets called.
You must check the log of your server for clues on what the root cause might be.

Related

How to add image into axios data

I would like to add an image into Axios data and send the data to .Net Controller. I have never done this before with an image and I need help.
The image source it's not coming from input, but from img tag.
Any idea how to insert the image into a JSON object(data)?
Thank you in advance!
function PostOffer(){
let localhost = "https://localhost:7009";
let url = localhost + "/Client/New";
let formClientName = document.getElementById("offer-client-name").value;
let formClientEmail = document.getElementById("offer-client-email").value;
let formClientPhone = document.getElementById("offer-client-phone").value;
let formClientDate = document.getElementById("offer-client-date").value;
let formClientTotal = document.getElementById("main-calculator-total-amount-final").innerText;
if(parseFloat(formClientTotal) > 0){
if(formClientName.trim() != "" && formClientEmail.trim() != "" && formClientPhone.trim() != "" && formClientDate.trim() != ""){
let data = {
clientName : formClientName,
clientEmail : formClientEmail,
clientOfferDate : formClientDate,
clientPhone : formClientPhone,
clientTotal : formClientTotal,
};
axios.post(url, data)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
ClearOfferSend();
}else{
document.getElementById("validation-inputs-send-offer").style.display = "flex";
}
}else{
document.getElementById("validation-inputs-send-offer").style.display = "flex";
document.getElementById("validation-inputs-send-offer").innerText = "Total amount can not be 0";
}
}
<div class="final-form">
<input type="text" asp-for="Name" id="offer-client-name" placeholder="name" required/>
<input type="email" asp-for="Email" id="offer-client-email" placeholder="email" required/>
<input type="text" asp-for="Phone" id="offer-client-phone" placeholder="phone" required/>
<label for="DateOffer">When do you want to start the project?</label>
<input type="date" asp-for="DateOffer" id="offer-client-date" placeholder="date" required/>
<div class="row">
<button class="btn-close-final-offer" onclick="CloseOfferForm();">Close</button>
<button class="btn-send-final-offer" onclick="PostOffer();">Send</button>
</div>
<span id="validation-inputs-send-offer">Inputs can not be empty!</span>
</div>
.NET controller:
[HttpPost]
public IActionResult New([FromBody] ClientAxiosModel offersend)
{
if (ModelState.IsValid)
{
_clientService.Create(offersend.clientName, offersend.clientEmail, offersend.clientPhone, offersend.clientOfferDate, offersend.clientTotal);
return Ok();
}
else
{
return NotFound();
}
}
If you use input type="file" you can insert image into axios with the following code:
<!-- HTML code -->
<input type="file" id="uploadImage" name="image">
// JS code
let formDataImage = document.getElementById("uploadImage").files[0];
// Add in data object too
data.image = formDataImage;

"The name 'msg' doesn't exist in the current context" - ASPX Error

I am programming a website as a part of my own project, and I have a registration form with a javascript validating first the email, password, fname, and etc and only then it submits the form. From there the c# takes over and checks if there is a user with such username in the database, and if there's I want to show an error as a paragraph in the registration form or show alert using JS.
Website:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="register.aspx.cs" Inherits="EquimaxSchool.register" %>
<section class="login-dark">
<form id="register" runat="server" method="post" >
<h2 class="sr-only">Login Form</h2>
<div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
<div class="form-group"><input class="form-control" type="text" name="username" placeholder="Username" runat="server" id="username"/></div> <!-- Username #11 -->
<div class="form-group"><input class="form-control" type="text" name="email" placeholder="Email" runat="server" id="email"></div> <!-- Email #1 -->
<div class="form-group"><input class="form-control" type="password" name="password" placeholder="Password" runat="server" id="password"></div> <!-- Password #2 -->
<div class="form-group"><input class="form-control" type="text" name="fName" placeholder="First Name" runat="server" id="fName" /></div> <!-- First Name #8 -->
<div class="form-group"><input class="form-control" type="text" name="lName" placeholder="Last Name" runat="server" id="lName" required/></div> <!-- Last Name #9 -->
<div class="form-group"><input class="form-control" type="date" name="birthdate" runat="server" id="birthdate" placeholder="Birthdate" required/></div> <!-- Birthdate #3 -->
<div class="form-group"><input class="form-control" title="Phone Number" name="phonenumber" placeholder="Phone Number" runat="server" id="phonenumber" /></div> <!-- Phone Number #4 -->
<span></span>
<div class="form-group"><select id="gender" name="gender" class="form-control" style="color:#6c757d" required>
<option value="Gender" disabled="disabled" selected="selected">Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select></div>
<div class="form-group"><select id="camera" name="camera-brand" class="form-control" style="color:#6c757d" required>
<option value="Camera Brand" disabled="disabled" selected="selected">Camera Brand</option>
<option value="Nikon">Nikon</option>
<option value="Canon">Canon</option>
<option value="Fuji">Fuji</option>
<option value="Sony">Sony</option>
<option value="Other">Other</option>
</select></div>
<div class="form-group"><input class="form-control" type="text" name="lens" placeholder="Lens" id="lens"/></div> <!-- Lens #10 -->
<div class="form-group"><select id="genre" name="genre" runat="server" class="form-control" style="color:#6c757d" required>
<option value="Sport">Sports</option>
<option value="Wildlife">Wildlife</option>
<option value="Landscape">Landscape</option>
<option value="Portrait">Portrait</option>
<option value="Architecture">Architecture</option>
</select></div>
<div class="form-group"><button class="btn btn-primary btn-block" type="submit" runat="server" id="submit">Sign up</button></div>
<%= msg %> <===== **THIS IS WHERE THE ERROR OCCURS**
</form>
(Please note I've redacted unnecessary tags and etc)
The JS of validation of form:
<script lang="javascript" type="text/javascript">
function validationCheck() {
var summary = "";
summary += isvalidpassword();
summary += isvalidFirstname();
summary += isvalidEmail();
summary += isvalidphoneno();
if (summary != "") {
alert(summary);
return false;
} else {
return true;
}
}
function isvalidpassword() {
var id;
var temp = document.getElementById("password");
id = temp.value;
if (id == "") {
return ("Password can't be empty" + "\n");
} else if (id.length > 1 && id.length < 8) {
return ("Password can't be shorter than 8" + "\n");
} else {
return "";
}
}
function isvalidFirstname() {
var id;
var temp = document.getElementById("fName");
id = temp.value;
if (id == "") {
return ("First name can't be empty" + "\n");
} else {
return "";
}
}
function isvalidEmail() {
var id;
var temp = document.getElementById("email");
id = temp.value;
var re = /\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
if (id == "") {
return ("Email can't be empty" + "\n");
} else if (re.test(id)) {
return "";
} else {
return ("Email invalid" + "\n");
}
}
function isvalidphoneno() {
var id;
var temp = document.getElementById("phonenumber");
id = temp.value;
var re;
re = /^[0-9]+$/;
var digits = /\d(10)/;
if (id == "") {
return ("Phone number can't be empty" + "\n");
} else if (re.test(id)) {
return "";
} else {
return ("Phone number should be digits only" + "\n");
}
}
$(document).ready(function () {
$("#register").submit(function (event) {
if (!validationCheck()) {
event.preventDefault();
}
});
});
</script>
The code behind it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace EquimaxSchool
{
public partial class register : System.Web.UI.Page
{
public string msg = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["submit"] != null)
{
string email = Request.Form["email"];
string password = Request.Form["password"];
string gender = Request.Form["gender"];
string fName = Request.Form["fName"];
string lName = Request.Form["lName"];
string phoneNumber = Request.Form["phonenumber"];
string camera = Request.Form["camera-brand"];
string birthdate = Request.Form["birthdate"];
string genre = Request.Form["genre"];
string username = Request.Form["username"];
string fileName = "UsersData.mdf";
string tableName = "usersTbl";
string sqlSelect = "SELECT * FROM " + tableName + " WHERE Username = '" + username + "'";
if (Helper.IsExist(fileName, sqlSelect))
{
msg = "Username has been taken already.";
}
}
}
}
}
Helper.cs for those asking
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
/// <summary>
/// Summary description for Helper
/// </summary>
///
public class Helper
{
public static SqlConnection ConnectToDb(string fileName)
{
string path = HttpContext.Current.Server.MapPath("App_Data/") + fileName;
//string connString = #"Data Source=.\SQLEXPRESS;AttachDbFileName=" + path + ";Integrated Security=True;User Instance=True";
//string connString = #"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = |DataDirectory|\" + fileName + " Integrated Security = True";
//string connString = #"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = " + path + " Integrated Security = True";
//string connString = #"";
string connString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + path + ";Integrated Security=True;Connect Timeout=30";
SqlConnection conn = new SqlConnection(connString);
return conn;
}
public static void DoQuery(string fileName, string sql)
{
SqlConnection conn = ConnectToDb(fileName);
conn.Open();
SqlCommand com = new SqlCommand(sql, conn);
com.ExecuteNonQuery();
conn.Close();
}
public static bool IsExist(string fileName, string sql)
{
SqlConnection conn = ConnectToDb(fileName);
conn.Open();
SqlCommand com = new SqlCommand(sql, conn);
SqlDataReader data = com.ExecuteReader();
bool found = Convert.ToBoolean(data.Read());
conn.Close();
return found;
}
public static DataTable ExecuteDataTable(string fileName, string sql)
{
SqlConnection conn = ConnectToDb(fileName);
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter tableAdapter = new SqlDataAdapter(sql, conn);
tableAdapter.Fill(dt);
return dt;
}
}
https://i.stack.imgur.com/b5GmQ.png
Your page inherits the class 'EquimaxSchool.login'
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="register.aspx.cs" Inherits="EquimaxSchool.login" %>
However, your C# class is named 'EquimaxSchool.Webform1'
namespace EquimaxSchool
{
public partial class WebForm1 : System.Web.UI.Page
{
Have you shown us the correct codebehind file? Is there a class called 'login' in the register.aspx.cs file?

How to keep the existing image if no new image selected?

I know there are similar questions. But I spend a whole day and couldn't fix my problem, Because I am completely noob. So, I'd appreciate it if someone provide an specific solution for my ASP.Net Core project.
If you need more info, Just ask.
Thanks.
So, My project is about Directors:
public class Director
{
public Director()
{
Movies = new List<Movie>();
}
public int DirectorId { get; set; }
[Required]
public string Name { get; set; }
public string Country { get; set; }
public string Bio { get; set; }
public List<Movie> Movies { get; set; }
public string PhotoURL { get; set; } // This field holds only the name of the photo, Not its URL.
}
My project save images in "wwwroot/uploads". Each director has an image. I can select a new image from my hard disk for each director.
Problem:
I can update a director image. But If I don't select a new image, the existing image will be deleted. I want to prevent it. I want it to keep the existing image if I don't select a new image.
Edit.cshtl.cs
public class EditModel : PageModel
{
private readonly Context _context;
private readonly IWebHostEnvironment hostingEnvironment;
public EditModel(Context context, IWebHostEnvironment environment)
{
_context = context;
this.hostingEnvironment = environment;
}
[BindProperty]
public Director Director { get; set; }
[BindProperty]
public IFormFile Image { set; get; }
public async Task<IActionResult> OnGetAsync(int? directorId)
{
if (directorId == null)
{
return NotFound();
}
Director = await _context.Director.FirstOrDefaultAsync(m => m.DirectorId == directorId);
if (Director == null)
{
return NotFound();
}
return Page();
}
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync(int? directorId)
{
if (!ModelState.IsValid)
{
return Page();
}
if (this.Image != null)
{
var fileName = GetUniqueName(this.Image.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, fileName);
this.Image.CopyTo(new FileStream(filePath, FileMode.Create));
this.Director.PhotoURL = fileName; // Set the file name
}
_context.Attach(Director).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!DirectorExists(Director.DirectorId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
private bool DirectorExists(int id)
{
return _context.Director.Any(e => e.DirectorId == id);
}
private string GetUniqueName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_" + Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
Edit.cshtml
<form method="post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Director.DirectorId" />
<div class="form-group">
<label asp-for="Director.Name" class="control-label"></label>
<input asp-for="Director.Name" class="form-control" />
<span asp-validation-for="Director.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Director.Country" class="control-label"></label>
<input asp-for="Director.Country" class="form-control" />
<span asp-validation-for="Director.Country" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Director.Bio" class="control-label"></label>
<input asp-for="Director.Bio" class="form-control" />
<span asp-validation-for="Director.Bio" class="text-danger"></span>
</div>
<div>
<img id="blah" src="~/uploads/#Model.Director.PhotoURL" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" runat="server">
<label asp-for="Director.PhotoURL" class="control-label"></label>
<input type="file" asp-for="Image" class="form-control" id="imgInp" value="~/uploads/#Model.Director.PhotoURL" />
<span asp-validation-for="Director.PhotoURL" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
site.js:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]); // convert to base64 string
}
}
$("#imgInp").change(function () {
if ($('#imgInp').get(0).files.length !== 0) {
readURL(this);
}
});
Edit page:
The simplest way to modify your code would be to do a get on the database and set the image path to the original image path if the new image path is null. This does have the disadvantage of an extra database call though:
if (this.Image != null)
{
...
}
else
{
Director.PhotoURL = (await _context.Director.FirstOrDefaultAsync(m => m.DirectorId == directorId))?PhotoURL;
}
Another option would be to store the original image path somewhere when you retrieve it from the database and then use it if the new image path is null. This would not involve an extra get. You could do something like:
[BindProperty]
public string OriginalImage { set; get; }
...
OriginalImage = Director.PhotoURL
...
<input type="hidden" asp-for="OriginalImage"/>
...
if (this.Image != null)
{
...
}
else
{
Director.PhotoURL = OriginalImage;
}
The simplest thing to do is to use an else clause in your OnPostAsync call here: if (this.Image != null)
Since you are setting the context to changed and doing an update, you are writing a null to the image. With an else you can do something like this:
else {
this.Director.PhotoURL = LastImage;
}
As for how you get a value for LastImage, the easiest way is to pull it via a linq query using the DirectorId that was passed in (the same way you get the Director object a little above).

Trouble accessing data passed from another view, using MVC

I am attempting to pass data from one view to the other using MVC. I am trying to do a simple guessing game, where on the first view, we enter a range of numbers, then on the second view we try to guess the number. I am able to store the values in my model, but I'm having trouble accessing them/using them in a js script on another view. Sorry if this is too much code, MVC's are hard to ask for help on without showing a full range of code. When I go to the second view to guess the number, it doesn't recognize #ViewBag.(model => model.Low) and it says Load is not defined
Model
pubblic class Range
{
public int High
{
get
{
if (HttpContext.Current.Session["High"] == null)
{
HttpContext.Current.Session["High"] = 3;
}
return (int)HttpContext.Current.Session["High"];
}
set
{
HttpContext.Current.Session["High"] = value;
}
}
public int Low
{
get
{
if (HttpContext.Current.Session["Low"] == null)
{
HttpContext.Current.Session["Low"] = 1;
}
return (int)HttpContext.Current.Session["Low"];
}
set
{
HttpContext.Current.Session["Low"] = value;
}
}
}
Controller
public class GuessingGameController : Controller
{
public ActionResult EnterRange()
{
return View();
}
[HttpPost]
public ActionResult EnterRange(Range range)
{
int high = range.High;
int low = range.Low;
return View(range);
}
public ActionResult GuessNumber()
{
return View();
}
}
View 1: Enter Range
#model GameMVC.Models.Range
#using (Html.BeginForm("EnterRange", "GuessingGame"))
{
<center>
<h2>Lets play a game.</h2>
Enter A Range of Numbers:
<br />
Low: #Html.TextBoxFor(m => m.Low)
<br />
High: #Html.TextBoxFor(m => m.High)
<br />
<input type="submit" value="Enter"/>
<p>
#Html.ActionLink("Now, To the Game", "GuessNumber", "GuessingGame")
</p>
</center>
}
View 2: Guess Number
#model GameMVC.Models.Range
<script language="JavaScript">
var myNum, count;
function Load() {
document.game.status.value = "Please set range of numbers and press the Start button.";
document.game.number.focus();
}
function Round(scale) {
var dd = new Date();
return((Math.round(Math.abs(Math.sin(dd.getTime())) * 8.71 * scale) % scale));
}
function myRange() {
var to = 1 + 1 * #ViewBag.(model => model.Low);
count = 0;
myNum = Round(to);
while (myNum < #ViewBag.(model => model.High);)
myNum = Round(to);
document.game.status.value = "Please guess a number, enter it, and press Guess.";
}
function Guess() {
var numberGuess = document.game.number.value;
count++;
if (numberGuess < myNum) alert("My number is greater than " + numberGuess + ".");
else if (numberGuess > myNum) alert("My number is less than " + numberGuess + ".");
else alert("It takes you " + count + " attempts to guess this number");
}
</script>
<body onload=" Load() ">
<div style="text-align: center;">
<form name=game>
Guess: <input type="text" name="number" size=10>
<p>
<br/>
<input type="button" value="Guess" onclick=" Guess() ">
</p>
#Html.Label("status")
</form>
</div>
</body>
Instead of #ViewBag.(model => model.Low), you could try just using #Model.Low
Model instance is not provided for "GuessAction" view. You need to pass an instance of "Range" to "GuessNumber" view. Since you are accessing values from session, you can simply pass a new instance.
public ActionResult GuessNumber()
{
return View(new Range());
}
Then in javascript you can simply access the data as #Model.High and #Model.Low
You can also use TempData to store the high and low values if you need it only for one request.

Pass value from Javascript function to MVC Model

I have the following ViewModel:
namespace SimpleModel.ViewModels
{
public class ClientSearch
{
public int Type { get; set; }
public string String { get; set; }
}
}
The following is the HTML code snippet:
<div id="clientSelect">
<input type="radio" name="clientSelect" value="1" />Account Number<br />
<input type="radio" name="clientSelect" value="2" />ID Number / Company Number<br />
<input type="radio" name="clientSelect" value="3" />Surname / Company Name<br />
#Html.EditorFor(model => model.String)
</div>
<p>
<input type="submit" value="Search" onclick="clientSearch('clientSelect')" />
</p>
I have the following JavaScript function:
<script type="text/javascript">
function clientSearch(strGroupName) {
var selectedValue = 0;
var arrInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oCurInput = arrInputs[i];
if (oCurInput.type == "radio" && oCurInput.name == strGroupName && oCurInput.checked)
selectedValue = oCurInput.value;
}
}
</script>
I need to update ClientSearch model Type field with selectedValue from within the Javascript function so I may pass the model back to the Controller for processing.
Any help would be appreciated.
First of all this object is not ok, you can not have a property that is a c# keyword
public class ClientSearch
{
public int Type { get; set; }
public string String { get; set; } // This right here is a reserved c# keyword
}
So change your ClientSearch class to something like
public class ClientSearch
{
public int Type { get; set; }
public string SearchString { get; set; }
}
Then your View will look something like:
<div id="clientSelect">
#Html.RadioButtonFor(x => x.Type, 1) #:AccountNumber<br/>
#Html.RadioButtonFor(x => x.Type, 2) #:ID Number / Company Number<br/>
#Html.RadioButtonFor(x => x.Type, 3) #:Surname / Company Name<br />
#Html.TextBoxFor(model => model.SearchString)
</div>
<p>
<input type="submit" value="Search" />
</p>
No javascript needed... imagine that :)

Categories

Resources