Html.Actionlink shows my model data - c#

I'm passing my model to actionlink using that
#Html.ActionLink("download", "action", "controller", Model, null)
But it generates html
<a href="/secure/action/controller?PrivateNo=3123123&LastName=lastname ..... >download</a>
So if user will change something it will affect to passed parameter and it will serious vulnerability. How can I avoid that?
as asked in comments i provide more details about controller.
public ActionResult List(MyModel model)
{
if (ModelState.IsValid)
{
bla bla bla
MyModel myModel = new MyModel()
{
PrivateNo = PrivateNumber,
FirstName = FirstName,
...
};
...
}
...
}
and in view I have
#Html.ActionLink("download", "GenerateDoc", "controller", Model, null)
and it goes to action which generates pdf
public ActionResult GenerateDoc(MyModel pdfModel)
{
string pdfData = FillTemplate(pdfModel);
byte[] source = Encoding.UTF8.GetBytes(pdfData);
byte[] resultDoc = Convert(source, "Template.xml");
return File(resultDoc, "application/pdf", Server.UrlEncode("test.pdf"));
}

Please achieve this by using form approach in your code Please refer below code:
On .cshtml/View page you have to put hidden fields (if you don't want to show these properties on page, it can also work for TextBoxes) for your Properties like below:
#using(Html.BeginForm("Index","Home",FormMethod.Post))
{
#Html.HiddenFor(x=>x.PrivateNo)
#Html.HiddenFor(x=>x.FirstName)
#Html.HiddenFor(x=>x.LastName)
<input type="submit" name="Submit" title="Submit" value="Submit" />
}
and on Controller you can get these values by following code:
[HttpPost]
public ActionResult Index(MyModel model)
{
return View();
}
after that you will get all the values on controller :
See below :
as you can see we have got the values from view to controller and no parameter is shown in URL.
Hope it helps you..:)
Thanks.
Happy coding :)

Related

how to take input from TextBox and show in view in MVC

I want to show one TextBox. In that if give any input string and button clicked it should so like this
hai , what is ur name
[TextBox]
welcome,ur name is "xyz"
I am new in MVC. Please help me to do this.
View
#{
ViewBag.Title = "MyPage";
}
<h2>Mymethod</h2>
<h3>#ViewBag.Message</h3>
#Html.TextBox("Name")
<form method="post">
<input type="submit" value="Submit" name="btn" />
</form>
HomeController.cs
public ActionResult Mymethod()
{
ViewBag.Message = "Hello what is ur name ??? ";
return View();
}
There are many ways to do this to accomplish what you want. I will provide you with a simplistic approach, please modify and change it to fit in with your scenario.
I would normally recommend using a view model above any other way, for example using a single string value or using FormCollection or ViewBag. They can work but I prefer to use view models.
I answered a question on what view models are and what they are supposed to do, please read it:
What is ViewModel in MVC?
First you will create a view model that will handle your input data, like first name, last name, age, etc. You will then pass this view model through to the view. In your example I will only include name:
public class ViewModel
{
public string Name { get; set; }
}
In your Create action method you will instantiate this view model and pass it to the view. And when you click on the button to submit the form then the post action method will receive this view model as input parameter:
public ActionResult Create()
{
ViewModel model = new ViewModel();
return View(model);
}
[HttpPost]
public ActionResult Create(ViewModel model)
{
if (!ModelState.IsValid)
{
// If validation fails send the view model back to the view and fix any errors
return View(model);
}
// Do what you need to do here if there are no validation errors
// In your example we are posting back to the current view to
// display the welcome message
return View(model);
}
And then finally you view will look like this:
#model Project.Models.ViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.Name)
<button type="submit">Submit</button>
if (!string.IsNullOrWhiteSpace(Model.Name))
{
<p>welcome, your name is #Model.Name</p>
}
}
Please spend some time reading through the many online tutorials on ASP.NET MVC.
Modify your current view to
#using(Html.BeginForm("ControllerName","Mymethod",FormMethod.Post))
{
<input type="submit" value="Submit" name="btn" />
}
Add another action method in your controller like this :
[HttpPost]
public ActionResult Mymethod(FormCollection form)
{
string Name = form["Name"];
Viewbag.Name = Name;
return View()
}
Then add view to this controller and write this into it.
Hi , Your Name is #Viewbag.Name
You should wrap your form in form tag. It is a form after all. So when you click submit, you are submitting the form.
<form method="post">
<h2>Mymethod</h2>
<h3>#ViewBag.Message</h3>
#Html.TextBox("Name")
#if (!String.IsNullOrEmpty(ViewBag.Name))
{
<h3>
welcome,ur name is #ViewBag.Name
</h3>
}
<input type="submit" value="Submit" name="btn" />
</form>
On the controller, you need to add HttpPost handler for your Mymethod action. This is where your web server is accepting the form you've submitted.
[HttpPost]
public ActionResult Mymethod(string name)
{
ViewBag.Message = "Hello what is ur name ???";
ViewBag.Name = name;
return View();
}

Mvc View rendering

I'm trying to create contact us page where user fill's in the detail and submit and at the bottom display message which comes from server.
The way i have implemented is something like this.
[HttpGet]
public ActionResult ContactUs()
{
//Process the stuff
return View("~Views/Contact/Contact.cshtml", model)
}
now when page load it hits above method and display form with the layout including header and footer.
Once user submits form it hits below method
[HttpPost]
public ActionResult ContactUs(ContactUs form)
{
//Process the stuff
View.Message="Thank you for your enquiry."
return View("~Views/Contact/Contact.cshtml", model)
}
It returns to the same page but it doesnt render the body layout not even header or footer simply display outputs form.
Not sure what im doing wrong there, is there any better approach ?
Thanks
Based on the code above, I believe you're attempting something like:
public class UxController : Controller
{
public ActionResult WithResponse(ActionResult result, string message)
{
PageResponse(message);
return result;
}
protected void PageResponse(string message)
{
TempData["Ux_Response"] = message;
}
}
That would be your Controller, then the Controller for that specific page, it would look like:
public class HomeController : UxController
{
public ActionResult Index()
{
return View();
}
public ActionResult SubmitForm(string message)
{
return WithResponse(RedirectToAction("Index"), "Thank you for feedback.");
}
}
Then in your front-end code, you would do the following:
#if(TempData["Ux_Response"] != null)
{
<div>#TempData["Ux_Response"]</div>
}
<form action="/Home/SubmitForm" method="post">
<input type="text" name="message" />
<input type="submit" value="Submit" />
</form>
Obviously you could enhance this, with more versatility. However, you're relying on Post, which will cause a screen flicker. So the better route, may be to do Ajax, then return a JsonResult. Hopefully this helps you out.
It should work if you change your controller/view like this.
Controller;
public ActionResult Contact(ContactModel model)
{
ViewBag.Message = "Your contact page.";
return View(model);
}
public ActionResult SaveContact(ContactModel model)
{
//process values in your model and then rest model
ContactModel.Message = "Thank you for contacting us"; //show thank you message
return RedirectToAction("Contact",model);
}
View;
#model MvcApplication1.Models.ContactModel
#{
ViewBag.Title = "Contact";
}
#using (Html.BeginForm("SaveContact", "Home", Model, FormMethod.Post))
{
#Html.DisplayFor(m => m.Message);
<button type="submit">Submit</button>
}
I manged to solve this. the issue was the because i was using sitecore cms the form action wasnt processing it full work flow, after i removed the action, it defaults to action method which defined in cms and triggers the cms workflow.

get a variable passed to my controller from a textbox

I have a simple model I am using for a search page to do some validation:
public class Search {
[Required]
[DisplayName("Tag Number")]
[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Tag must be a number")]
public int HouseTag { get; set; }
i then have a simple view with a textbox and a submit button:
#model Search
#{
Layout = "~/_Layout.cshtml";
}
#using (Html.BeginForm("Search", "Inquiry", FormMethod.Get)){
#Html.LabelFor(m =>m.HouseTag)
#Html.TextBoxFor(m=>m.HouseTag, new { type = "Search", autofocus = "true", style = "width: 200px", #maxlength = "6" })
<input type="submit" value="Search" id="submit"/>
my controller is expecting a parameter of an id:
[HttpGet]
public ActionResult Search(int id){
ViewBag.Tag = id;
return View();
}
when i execute it with a number i get a null value being passed to the controller, causing things to blow up. I am using the model to control some of the properties of the search box for validation. I used to just have #Html.TextBox and it returned fine, but now that ive added the model, it doesnlt return anything.
You can set your parameter to a type of Search and then access the property in your action
[HttpGet]
public ActionResult Search(Search model){
ViewBag.Tag = model.HouseTag;
return View();
}
If it were me I'd make this a HttpPost or create a seperate action for this form so I wouldn't see the HouseTag text in the URL..
#using (Html.BeginForm("Search", "Inquiry", FormMethod.Post))
{
#Html.LabelFor(m => m.HouseTag)
#Html.TextBoxFor(m => m.HouseTag, new { type = "Search", autofocus = "true", style = "width: 200px", #maxlength = "6" })
<input type="submit" value="Search" id="submit" />
}
[HttpPost]
public ActionResult Search(Search model){
ViewBag.Tag = model.HouseTag;
return View();
}
You are expecting a parameter named id and you are passing HouseTag as the name of that parameter you should rename id to houseTag inside the Search method.
There's a couple of things going on here. First you are going to want to split your Get and Post actions. Also forms are only used in conjunction with POST's. You also don't need to name your action or controller unless you are sending the post to a different controller or action then the GET.
This is the get. It renders the form on the page. You don't need to put [HttpGet] on there, it is the default.
public ActionResult Search()
{
return View();
}
The following is going to post the form back to the server. the model binder will wire up the html form fields with your view model. since you have validators on the view model, you'll want to check that the model state is valid and re-show the view with the associated errors. You will need to add an #Html.ValidationMessageFor(...) into your view so that you actually see those errors.
[HttpPost]
public ActionResult Inquiry(Search search)
{
if (!ModelState.IsValid)
{
return View(search);
}
//so something with your posted model.
}

How to pass the value of the variable from get to post MVC

Get method:
public ActionResult Add(string id)
{}
I want to read the value of the variable "id" in the method of post
[HttpPost]
public ActionResult Add(List<class_of_data> clazz)
{}
Basically you could do something like this:
public ActionResult Add(string id)
{
ViewBag.ModelId = id;
return View();
}
[HttpPost]
public ActionResult Add(List <class_of_data> classList, string id)
{
// you can set int id if you need it as an number since MVC will convert it.
// Also keep in mind that class in a reserved keyword. Changed it to classList
// DO SOME STUFF
}
And the View should be something like:
#using(Html.BeginForm())
{
// some code
<input type='hidden' name='id' value='#ViewBag.ModelId' />
// some code
}
If your are submit a form and wish to have lose model binding or there is no model binding, then this solution might be useful for you.
[HttpPost]
public ActionResult FormSubmit(FormCollection form)
{
string id= form["id"].ToString();
return RedirectToAction("Index");
}
}
And your view should look something like this
<input type="textbox" name="id" />
<input type="submit" Value="Submit Form" />
Hope this solution works for you.

Html.CheckBox Helper passes null to the calling controller

Is there a reason why my Html.CheckBox() View control is returning null up to the Controller ?
Can't seem to figure this one out and would appreciate any help !
View:
#{ Html.BeginForm("ActionName", "ControllerName", FormMethod.Get); }
Enter Text: #Html.TextBox("Code", string.Empty, new { id = "Code" })
<input type="submit" value="GO" />
<span style="padding-left:20px; font-size:14px" >#Html.CheckBox("exactMatch", false, new { id = "textmatches" })
&nbspText exact match</span>
#{ Html.EndForm(); }
Controller that gets called upon submitting the form:
public ActionResult ActionName(string code,bool boxChecked)
{
return View(ServiceCallGoesHere(code.Trim(),boxChecked));
}
I can't figure out why in the world is my checkbox status not being passed to the controller. Why is boxChecked parameter in the controller always = null ? How can I resolve this problem ?
Thank you in advance !
As far as I know when the view post back the data MVC framework uses the id of form controls to map them with the parameters of an action of your controller.Maybe that's why you can't get the right data
change
public ActionResult ActionName(string code,bool boxChecked)
{
return View(ServiceCallGoesHere(code.Trim(),boxChecked));
}
to
> public ActionResult ActionName(string code,bool exactMatch)
{
return View(ServiceCallGoesHere(code.Trim(),exactMatch));
}

Categories