I am having a slight little problem and wondering is there anyway that you could help me?
I am passing information using angularJs to an MVC controller. I am passing an Id of a user to the controller to allow the admin to change the user into an administrator.
Here is the code for the view,
<tr ng-repeat="r in students | filter : searchStudent">
<td><input type="text" name="Id" value="{{r.ID}}" readonly id="AdminIdText" /></td>
<td>{{r.username}}</td>
<td>{{r.Email}}</td>
<td>{{r.AccountStatus}}</td>
<td>test</td>
<td><input type="submit" value="Make Admin" class="btn btn-warning" /></td>
</tr>
Here is the controller,
public ActionResult AdminStatus(int id)
{
int Id = id;
//Connection to the database
var db = WebMatrix.Data.Database.Open("Database");
db.Execute("UPDATE tblaccount SET AccountStatus= 1 WHERE ID =" + id);
db.Close();
return View("AddAdministrator");
}
}
What I am wondering is, how do you retrieve the numeric value that has been passed through to the controller? This is because placing the information into a model is not working correctly.
Thanks in advance
I think you need to do 2 things. Make the <a> tag look something like this:
<a href="Action/{{r.ID}}">
And add a controller method like this:
public ActionResult Action(int id)
{
// Do something with the id
}
As long as the default route maps are set up in the MVC project, that should map the id value to the id parameter.
Use the MVC 'UrlHelper' to generate URLs that keep working even after controllers have been moved around:
#Url.Action("<ActionName>", "<ControllerName>", new { Area = "<AreaName>", parameter1 = parameter1Value, parameter2 = parameter2Value })
For example:
#Url.Action("AdminStatus", "Admin", new { Area = "Admin", id = r.ID})
will hit the "AdminStatus" action in the "AdminController" in the Area named "Admin" and send a parameter named "id".
you can also use name attribute to get the id value to your controller method.
public void action(int Id)
{
// your code
}
Related
I'm learning to develop a webapp using .net and I'm having a problem in retrieving the value from an <input>
Size:
#using (Html.BeginForm("GetList", "User", FormMethod.Post))
{
#Html.TextBoxFor(Model => Model.PageSize)
<input type="submit" value="Invia" />
}
I want to retrieve the value posted and then use it as a parameter in the url but all I try isn't working and all this is frustrating me a lot, thanks for the help.
In your Post method in the Controller, define an input variable with the same datatype of the model that you are using in the view. Then you will be able to get the values that you have on the screen.
What happens is that when the submit button is pressed, all the input values will be submitted to Controller's post method.
Supposing that your model's datatype is "User", the Controller's Post method should look like the below:
[HttpPost]
public ActionResult GetList(User model)
{
int pageSize = model.PageSize;
...
return View();
}
I'm attempting to, on the click of a button, complete a to-do item, therefore removing it from the list.
I'm using an ActionLink for the button:
#foreach (var item in Model)
{
<li class="#item.Priority">
#item.Text
<div class="agile-detail">
#Html.ActionLink("Done", "Complete", "Home", new { id = item.ToDoId }, new { #class = "pull-right btn btn-xs btn-primary" })
<i class="fa fa-clock-o"></i> #item.Date
</div>
</li>
}
And a very short action for the processing in the controller:
public ActionResult Complete(int todoId)
{
using (var db = new KnightOwlContext())
{
DashboardHelper dashboardHelper = new DashboardHelper(db);
dashboardHelper.CompleteToDo(todoId);
return RedirectToAction("Index", "Home");
}
}
Clicking the button generated a URL of:
http://site/Home/Complete/1
I've looked up a solution and so far it looks like it could be any number of issues. Also the ActionLink button is inside a partial view so I'm not sure if that changes anything in terms of incorrect routing setup? For routing too I'm just using the default config that comes with an MVC project in Visual Studio.
Just having trouble narrowing down the cause of the issue so where to check first?
The parameter in your method is int todoId but you not passing any value for that - your only passing a value for a parameter named id.
Change the method to
public ActionResult Complete(int id)
or change the link to use new { todoId = item.ToDoId }, but that will add a query string value, not a route value, unless you create a specific route definition with url: "Home/Complete/{todoId}"
I have a URL like this
http://localhost/PW/LeaveWithoutPay/Edit?id=9
and I want to hide the id?=9 from my URL. Can any one demonstrate how to hide this id parameter with an example? I am using Visual Studio 2012.
You must need to implement Post method instead of GET method. Here is a sample example for it.
In your controller define something like this
public ActionResult Edit([FromBody] int id) {
TempData["MsgText"] = id.ToString();
return RedirectToAction("Index");
}
Now in your view, implement the POST method. A sample example is:
#{string id =(string)TempData["MsgText"];}
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "frmCallThis" })){
#Html.Label("label",string.IsNullOrEmpty(id)?"No Id Provided":"Current ID = " + id)
#Html.TextBox("id");
<input type="submit" value="Get This Printed" />
}
Finally you have the following output: (Before Submit)
And After submit:
Hope this helps,
Only one thing you have to doing here is using POST, not GET method. Because the web request is usually stateless, so I don't think we have any other methods to hide your id.
I am trying to set up a simple login html page, whose action is sent to mvc controller on another of my sites. I have no problem setting up the page to do the post, and in the mvc controller I have my method that reads the form post. The problem is that I am not seeing my fields from the html form in the form collection.
Is there something special that I need to do to read a form post within a mvc controller method, if so what is that?
The is the form action markup from my page
<form action="http://reconciliation-local.sidw.com/login/launch" method="post">
User Name <input type="text" id="username"/><br/>
Password <input type="text" id="password"/>
<input type="submit" value="launch"/>
</form>
The controller method
[HttpPost]
public ActionResult launch(FormCollection fc)
{
foreach (string fd in fc)
{
ViewData[fd] = fc[fd];
}
return View();
}
When I step through the controller method code, I am not seeing anything in the formcollection parameter.
Post Html To MVC Controller
Create HTML page with form (don't forget to reference a Jquery.js)
<form id="myform" action="rec/recieveData" method="post">
User Name <input type="text" id="username" name="UserName" /><br />
Password <input type="text" id="password" name="Password"/>
<input type="submit" id="btn1" value="send" />
</form>
<script>
$(document).ready(function () {
//get button by ID
$('#btn1').submit(function () {
//call a function with parameters
$.ajax({
url: 'rec/recieveData', //(rec)= Controller's-name
//(recieveData) = Action's method name
type: 'POST',
timeout: '12000', (optional 12 seconds)
datatype: 'text',
data: {
//Get the input from Document Object Model
//by their ID
username: myform.username.value,
password: myform.password.value,
}
});
});
});
</script>
Then in The MVC Controller
controller/action
| |
1. Create Controller named rec (rec/recieveData)
Create View named rec.cshtml
Here is the controller:
public class recController : Controller
{
// GET: rec
string firstname = "";
string lastname = "";
List<string> myList = new List<string>();
public ActionResult recieveData(FormCollection fc)
{
//Recieve a posted form's values from parameter fc
firstname = fc[0].ToString(); //user
lastname = fc[1].ToString(); //pass
//optional: add these values to List
myList.Add(firstname);
myList.Add(lastname);
//Importan:
//These 2 values will be return with the below view
//using ViewData[""]object...
ViewData["Username"] = myList[0];
ViewData["Password"] = myList[1];
//let's Invoke view named rec.cshtml
// Optionaly we will pass myList to the view
// as object-model parameter, it will still work without it thought
return View("rec",myList);
}
}
Here is the View:
#{
ViewBag.Title = "rec";
}
<h2>Hello from server</h2>
<div>
#ViewData["Username"]<br /> <!--will display a username-->
#ViewData["Password"] <!-- will display a password-->
</div>
If you posted some code it would be much easier to help you, so please edit your question...
Make sure that your form's action has the correct address, that your method is specifying POST (method="POST") and that the input fields under your form have name attributes specified.
On the server side, try making your only parameter a FormCollection and test that the fields in your form posted through the debugger. Perhaps your model binding isn't correct and the FormCollection will at least show you what got posted, if anything.
These are just common issues I've seen. Your problem could be different, but we need to see what you're working with to be able to tell.
Try something like this:
cQuery _aRec = new cQuery();
_aRec.Sqlstring = "SELECT * FROM Admins";
DataSet aDS = _aRec.SelectStatement();
DataTable aDT = aDS.Tables[0];
foreach (DataRow aDR in aDT.Rows){
if (txtAdminUsername.Text == aDR[0].ToString()){
if (txtAdminPassword.Text == aDR[1].ToString()){
Session["adminId"] = aDR[0];
Response.Redirect("Admin.aspx");
return;
}
}
}
Make sure that your FormCollection object properties for username and password are defined properly.
I had to use the name attribute on the text tag, and that solved my problem, is now working like a charm.
You have to use Ajax to do that.. Whenever you want to "submit" from client side, you should use Ajax to update the server
Step 1 - you redirect your Ajax call to your action, but with your list of parameters in the query-string appended
$.ajax(url: url + "?" + your_query_string_parameter_list_you_want_to_pass)
Step 2 - add optional parameters to your Controller-action with the same names and types you expect to get returned by the client
public ActionResult MyControllerAjaxResponseMethod(type1 para1 = null,
type2 para2 = null,
type3 para3 = null, ..)
Know that the optional parameters have to be initialized, otherwise the Action itself will always ask for those
Here's where the "magic" happens though --> MVC will automatically convert the query-string parameters into your optional controller-parameters if they match by name
I was also looking for a good answer for this, --> i.e. - one that doesn't use q-s for that usage, but couldn't find one..
Kinda makes sense you can't do it in any other way except by the url though..
I am getting red x mark instead of the picture when storing in database. I believe I am having problems in the Views files. Please could someone have a look at this and tell me how to correct it. If I have wrong URL Actions please tell me which ones I should be using. Thanks in advance.
SubCategory2 Table has the following columns...
Column field > Picture1 : Data Type > varbinary(MAX)
Column field > ImageMimeType : Data Type > varchar(50)
Index.cshtml file
#foreach (var item in Model) {
<td>
<img src="#Url.Action("GetImage", "SubProductCategory2",
new { id = item.SubProductCategoryID})" alt="" height="100" width="100" />
</td>
Edit.cshtml file
"Edit" is the method in the contoller. "ProductCategoryL2" is the method in the controller. "GetImage" is the method in controller. All these methods are in the same controller file called ProductCategoryControllerL2
#using (Html.BeginForm("Edit", "ProductCategoryL2", "GetImage",
FormMethod.Post, new { #encType = "multipart/form-data" }))
{
<div class="editor-field">
<img src="#Url.Action("GetImage", "SubProductCategory2", new {
Model.SubProductCategoryID })" alt="" />
#Html.ValidationMessage("Picture1", "*")
<input type="file" id="fileUpload" name="Create" size="23"/>
</div>
}
ProductCategoryL2Controller.cs file
[HttpPost]
public ActionResult Edit(int id, FormCollection collection,
SubProductCategory2 editSubProdCat, HttpPostedFileBase image)
{
var r = db.SubProductCategory2.First(x => x.SubProductCategoryID
== id);
if (TryUpdateModel(r))
{
if (image != null)
{
editSubProdCat.ImageMimeType = image.ContentType;
editSubProdCat.Picture1 = new byte[image.ContentLength];
image.InputStream.Read(editSubProdCat.Picture1, 0,
image.ContentLength);
}
db.SaveChanges();
return RedirectToAction("/");
}
return View(r);
}
public FileContentResult GetImage(int productId)
{
var product = db.SubProductCategory2.First(x =>
x.SubProductCategoryID == productId);
return File(product.Picture1, product.ImageMimeType);
}
Addition Note
I am using MVC 3 framework. The GetImage method has been extacted from Steven Sanderson book Pro ASP.NET MVC 2 Framework. So I am not sure if that will be a problem?
The first step I would take to debug would be to try the URL for the image in your browser directly. Right-click on the red X, copy the url and paste it in your address bar. If the url looks right you should be a better error telling you what the problem is. If that fails, put a breakpoint in your GetImage routine to make sure the routes are correct and your method is getting called. Try Fiddler to see the request being made and what your web server is saying.
My guess is that you have the action wrong. It looks like you are linking to the GetImage action on the SubProductCategory2 controller when the method is on your ProductCategoryL2 controller.
Also I don't understand how your Model.SubProductCategoryID value is supposed to be mapped to your productId parameter. Try changing these calls:
Url.Action("GetImage", "SubProductCategory2",
new { id = item.ProductCategoryID})
Url.Action("GetImage", "SubProductCategory2", new {
Model.SubProductCategoryID })
to these:
Url.Action("GetImage", "ProductCategoryL2",
new { productId = item.ProductCategoryID})
Url.Action("GetImage", "ProductCategoryL2", new {
productId = Model.SubProductCategoryID })
Your input file field is called Create:
<input type="file" id="fileUpload" name="Create" size="23"/>
whereas the controller action parameter handling the form submission is called image (the one with HttpPostedFileBase type) => this parameter will always be null in your Edit controller action and nothing will be saved in the database.
Also the attribute is called enctype and not encType in the Html.BeginForm helper. Also inside the GetImage action ensure that product.Picture1 represents a correct image byte array and that it's content type matches with product.ImageMimeType.
So for example to further debug this issue you could try to save it to some temporary file to see if it is a valid image just before returning. Also make sure that the product instance you have fetched from the database is not null:
// if the content type is image/png:
File.WriteAllBytes(#"c:\foo.png", product.Picture1);
Then ensure that foo.png open successfully with an image viewer.
You are trying to return file content as the value to your img's src attribute. Your browser will need to issue a separate request for the image.
change your view to this:
<img src="GetImage/#(Model.SubProductCategoryID)" />