Reputation: 1015
I'm fairly new to asp.net mvc and I have a question. Example model:
public class FooModel
{
public string StrA {get; set;}
public string StrB {get; set;}
}
How can I do something like this: pass model to view (model with StrA filled, StrB empty), update StrB of my model (StrA filled, StrB filled) and then submit it to my action with both StrA and StrB filled (by default I will pass new instance of model with only StrB filled and my previous value of StrA will vanish).
I know I can use HiddenFor, but is there any other way to do that?
Upvotes: 0
Views: 3624
Reputation: 8417
You can build your own POST using e.g. jQuery AJAX ( http://api.jquery.com/jQuery.post/ ) or construct a form manually and submit it ( http://api.jquery.com/submit/ ). This means you won't have to create a visible form on the page (if that is what you want to avoid).
However you will need to pass the data to the DOM and persist it in some way (e.g. with a hidden field). Since HTML is stateless you can't magically save the StrA somewhere if you actually want to get it back to the server somehow - unless it isn't meant to change between requests, which means you wont need to get it to the client and back any way (see Darin's response for an example of how to handle it in this case).
Upvotes: 0
Reputation: 1039408
I know I can use HiddenFor, but is there any other way to do that?
In your POST action you could fetch the value of the StrA
property from the same place you fetched it in your GET action. This way you don't need to use a hidden field to persist it.
For example:
public ActionResult Index()
{
var model = new FooModel
{
StrA = PopulateStrAFromSomewhere()
};
return View(model);
}
[HttpPost]
public ActionResult Index(string strB)
{
var model = new FooModel
{
StrA = PopulateStrAFromSomewhere(),
StrB = strB
}
... do something with the model
}
Now in the view you could only have an input field for StrB
inside the form which will allow the user to modify its value:
@model FooModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.StrB)
@Html.EditorFor(x => x.StrB)
<button type="submit">OK</button>
}
Upvotes: 2